From b31cdb55422226cd45a2234a4b54986f1f611151 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 20 Sep 2009 20:59:52 +0200 Subject: AS guide: documents Enumerable#sum --- .../guides/source/active_support_overview.textile | 45 ++++++++++++++++++++++ 1 file changed, 45 insertions(+) (limited to 'railties/guides') 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: + + +[1, 2, 3].sum # => 6 +(1..100).sum # => 5050 + + +Addition only assumes the elements respond to +: + + +[[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] + + +The sum of an empty collection is zero by default, but this is customizable: + + +[].sum # => 0 +[].sum(1) # => 1 + + +If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values: + + +(1..5).sum {|n| n * 2 } # => 30 +[2, 4, 6, 8, 10].sum # => 30 + + +The sum of an empty receiver can be customized in this form as well: + + +[].sum(1) {|n| n**3} # => 1 + + +The method +ActiveRecord::Observer#observed_subclasses+ for example is implemented this way: + + +def observed_subclasses + observed_classes.sum([]) { |klass| klass.send(:subclasses) } +end + + h3. Extensions to +Array+ h4. Accessing -- cgit v1.2.3