Skip to content

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

instance method

Enumerable#sum

sum(initial_value = 0) → number
sum(initial_value = 0) {|element| ... } → object

With no block given, returns the sum of initial_value and the elements:

Example
(1..100).sum          # => 5050
(1..100).sum(1)       # => 5051
('a'..'d').sum('foo') # => "fooabcd"

Generally, the sum is computed using methods + and each; for performance optimizations, those methods may not be used, and so any redefinition of those methods may not have effect here.

One such optimization: When possible, computes using Gauss’s summation formula n(n+1)/2:

Example
100 * (100 + 1) / 2 # => 5050

With a block given, calls the block with each element; returns the sum of initial_value and the block return values:

Example
(1..4).sum {|i| i*i }                        # => 30
(1..4).sum(100) {|i| i*i }                   # => 130
h = {a: 0, b: 1, c: 2, d: 3, e: 4, f: 5}
h.sum {|key, value| value.odd? ? value : 0 } # => 9
('a'..'f').sum('x') {|c| c < 'd' ? c : '' }  # => "xabc"
See also #sort_by #take #sort #take_while also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0