Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#sum

array.sum(init = 0) → object
array.sum(init = 0) {|element| ... } → object

When no block is given, returns the object equivalent to:

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

For example, [e1, e2, e3].sum returns </tt>init + e1 + e2 + e3</tt>.

Examples:

Example
a = [0, 1, 2, 3]
a.sum # => 6
a.sum(100) # => 106

The elements need not be numeric, but must be +-compatible with each other and with init:

Example
a = ['abc', 'def', 'ghi']
a.sum('jkl') # => "jklabcdefghi"

When a block is given, it is called with each element and the block’s return value (instead of the element itself) is used as the addend:

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

Notes:

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