Skip to content
instance method

Array#sum

(?untyped init) -> untyped
(?untyped init) { (Elem e) -> untyped } -> untyped
sum(init = 0) → object
sum(init = 0) {|element| ... } → object

With no block given, returns the sum of init and all elements of self; for array array and value init, equivalent to:

Example
sum = init
array.each {|element| sum += element }
sum

For example, [e0, e1, e2].sum returns init + e0 + e1 + e2.

Examples:

Example
[0, 1, 2, 3].sum                 # => 6
[0, 1, 2, 3].sum(100)            # => 106
['abc', 'def', 'ghi'].sum('jkl') # => "jklabcdefghi"
[[:foo, :bar], ['foo', 'bar']].sum([2, 3])
# => [2, 3, :foo, :bar, "foo", "bar"]

The init value and elements need not be numeric, but must all be +-compatible:

Example
# Raises TypeError: Array can't be coerced into Integer.
[[:foo, :bar], ['foo', 'bar']].sum(2)

With a block given, calls the block with each element of self; the block’s return value (instead of the element itself) is used as the addend:

Example
['zero', 1, :two].sum('Coerced and concatenated: ') {|element| element.to_s }
# => "Coerced and concatenated: zero1two"

Notes:

See also #sort_by! #take #sort! #take_while also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0