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

Enumerable#sum

enum.sum(init=0) → number
enum.sum(init=0) {|e| expr } → number

Returns the sum of elements in an Enumerable.

If a block is given, the block is applied to each element before addition.

If enum is empty, it returns init.

For example:

Example
{ 1 => 10, 2 => 20 }.sum {|k, v| k * v }  #=> 50
(1..10).sum                               #=> 55
(1..10).sum {|v| v * 2 }                  #=> 110
('a'..'z').sum                            #=> TypeError

This method can be used for non-numeric objects by explicit init argument.

Example
{ 1 => 10, 2 => 20 }.sum([])                   #=> [1, 10, 2, 20]
"a\nb\nc".each_line.lazy.map(&:chomp).sum("")  #=> "abc"

If the method is applied to an Integer range without a block, the sum is not done by iteration, but instead using Gauss’s summation formula.

Enumerable#sum method may not respect method redefinition of “+” methods such as Integer#+, or “each” methods such as Range#each.

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