aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/active_support_overview.textile
diff options
context:
space:
mode:
authorXavier Noria <fxn@hashref.com>2009-09-21 23:27:48 +0200
committerXavier Noria <fxn@hashref.com>2009-09-21 23:27:48 +0200
commit3ed6b3a8b310598b391d004514ee72c58171d637 (patch)
tree8ae159b4679e4b4608453a80a976e1ecd9dc6a46 /railties/guides/source/active_support_overview.textile
parent340be9bddd8e5902e0218a0101a40a17a4afd558 (diff)
downloadrails-3ed6b3a8b310598b391d004514ee72c58171d637.tar.gz
rails-3ed6b3a8b310598b391d004514ee72c58171d637.tar.bz2
rails-3ed6b3a8b310598b391d004514ee72c58171d637.zip
AS guide: documents Enumerable#each_with_object
Diffstat (limited to 'railties/guides/source/active_support_overview.textile')
-rw-r--r--railties/guides/source/active_support_overview.textile24
1 files changed, 24 insertions, 0 deletions
diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile
index 48faf260c7..d09b8cde88 100644
--- a/railties/guides/source/active_support_overview.textile
+++ b/railties/guides/source/active_support_overview.textile
@@ -847,6 +847,30 @@ def observed_subclasses
end
</ruby>
+h4. +each_with_object+
+
+The +inject+ method offers iteration with an accumulator:
+
+<ruby>
+[2, 3, 4].inject(1) {|acc, i| product*i } # => 24
+</ruby>
+
+The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:
+
+<ruby>
+[1, 2].inject({}) {|h, i| h[i] = i**2; h} # => {1 => 1, 2 => 4}
+</ruby>
+
+See that spurious "+; h+"?
+
+Active Support backports +each_with_object+ from Ruby 1.9, which addresses that use case. It iterates over the collection, passes the accumulator, and returns the accumulator when done. You normally modify the accumulator in place. The example above would be written this way:
+
+<ruby>
+[1, 2].each_with_object({}) {|i, h| h[i] = i**2} # => {1 => 1, 2 => 4}
+</ruby>
+
+WARNING. Note that the item of the collection and the accumulator come in different order in +inject+ and +each_with_object+.
+
h3. Extensions to +Array+
h4. Accessing