aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/active_support_overview.textile
diff options
context:
space:
mode:
authorXavier Noria <fxn@hashref.com>2009-09-20 20:59:52 +0200
committerXavier Noria <fxn@hashref.com>2009-09-20 20:59:52 +0200
commitb31cdb55422226cd45a2234a4b54986f1f611151 (patch)
treee024652aa587661bf2a9eed99382d24b2a96f44c /railties/guides/source/active_support_overview.textile
parentc61bb08d0e95530086570bd1e2e874e36d6fb711 (diff)
downloadrails-b31cdb55422226cd45a2234a4b54986f1f611151.tar.gz
rails-b31cdb55422226cd45a2234a4b54986f1f611151.tar.bz2
rails-b31cdb55422226cd45a2234a4b54986f1f611151.zip
AS guide: documents Enumerable#sum
Diffstat (limited to 'railties/guides/source/active_support_overview.textile')
-rw-r--r--railties/guides/source/active_support_overview.textile45
1 files changed, 45 insertions, 0 deletions
diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile
index f9a2f5f963..48faf260c7 100644
--- a/railties/guides/source/active_support_overview.textile
+++ b/railties/guides/source/active_support_overview.textile
@@ -802,6 +802,51 @@ end
WARNING. Active Support redefines +group_by+ in Ruby 1.8.7 so that it still returns an ordered hash.
+h4. +sum+
+
+The method +sum+ adds the elements of an enumerable:
+
+<ruby>
+[1, 2, 3].sum # => 6
+(1..100).sum # => 5050
+</ruby>
+
+Addition only assumes the elements respond to <tt>+</tt>:
+
+<ruby>
+[[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
+%w(foo bar baz).sum # => "foobarbaz"
+{:a => 1, :b => 2, :c => 3}.sum # => [:b, 2, :c, 3, :a, 1]
+</ruby>
+
+The sum of an empty collection is zero by default, but this is customizable:
+
+<ruby>
+[].sum # => 0
+[].sum(1) # => 1
+</ruby>
+
+If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
+
+<ruby>
+(1..5).sum {|n| n * 2 } # => 30
+[2, 4, 6, 8, 10].sum # => 30
+</ruby>
+
+The sum of an empty receiver can be customized in this form as well:
+
+<ruby>
+[].sum(1) {|n| n**3} # => 1
+</ruby>
+
+The method +ActiveRecord::Observer#observed_subclasses+ for example is implemented this way:
+
+<ruby>
+def observed_subclasses
+ observed_classes.sum([]) { |klass| klass.send(:subclasses) }
+end
+</ruby>
+
h3. Extensions to +Array+
h4. Accessing