Module: Enumerable
- Defined in:
- lib/hobson/core_extensions/enumerable/sum.rb
Instance Method Summary collapse
-
#sum(identity = nil) ⇒ Object
Sums the elements of a collection by invoking their ‘+` method.
Instance Method Details
#sum(identity = nil) ⇒ Object
Sums the elements of a collection by invoking their ‘+` method.
The sum method is completely generic, it can work on any objects that respond to ‘+`.
["a", "b", "c"].sum #=> "abc"
It is a good idea to provide a default value. The default value also acts as an initial value.
[].sum #=> nil
[].sum(9) #=> 9
21 22 23 |
# File 'lib/hobson/core_extensions/enumerable/sum.rb', line 21 def sum(identity = nil) reduce(&:+) || identity end |