Module: Enumerable

Defined in:
lib/hobson/core_extensions/enumerable/sum.rb

Instance Method Summary collapse

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

Parameters:

  • identity (Object) (defaults to: nil)

    an optional default return value if there are no elements. It is nil by default.

Returns:

  • The sum of the elements or the default value if there are no elements.



21
22
23
# File 'lib/hobson/core_extensions/enumerable/sum.rb', line 21

def sum(identity = nil)
  reduce(&:+) || identity
end