mirror of
https://github.com/github/rails.git
synced 2026-04-26 03:00:59 -04:00
AS guide: documents Enumerable#sum
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user