How to Use sum in Ruby: Simple Guide with Examples
In Ruby, you can use the
sum method to add all elements of an array or range. Simply call sum on the collection, like [1, 2, 3].sum, which returns 6. You can also provide a starting value or a block for custom summing.Syntax
The sum method is called on an Enumerable like an array or range. It can be used in two main ways:
collection.sum- adds all elements starting from zero.collection.sum(initial)- starts adding from theinitialvalue.collection.sum(initial) { |element| block }- sums the result of the block applied to each element.
This method returns the total sum as a number.
ruby
array.sum array.sum(10) array.sum(0) { |x| x * 2 }
Example
This example shows how to sum numbers in an array, use a starting value, and sum squares of numbers using a block.
ruby
numbers = [1, 2, 3, 4, 5] # Sum all elements puts numbers.sum # Sum with a starting value puts numbers.sum(10) # Sum squares of elements puts numbers.sum(0) { |n| n * n }
Output
15
25
55
Common Pitfalls
Some common mistakes when using sum include:
- Calling
sumon an empty array without an initial value returns0, which is expected but sometimes surprising. - Using
sumon arrays with non-numeric elements without a block will cause errors. - For older Ruby versions (before 2.4),
sumis not available by default.
ruby
wrong = ['a', 'b', 'c'] # wrong.sum # This will raise an error # Correct way with block: correct = ['a', 'b', 'c'] puts correct.sum('') { |s| s.upcase }
Output
ABC
Quick Reference
| Usage | Description | Example |
|---|---|---|
| collection.sum | Sum all elements starting at 0 | [1,2,3].sum #=> 6 |
| collection.sum(initial) | Sum starting at initial value | [1,2,3].sum(10) #=> 16 |
| collection.sum(initial) { |e| block } | Sum results of block starting at initial | [1,2,3].sum(0) { |n| n*2 } #=> 12 |
Key Takeaways
Use
sum to add all elements in arrays or ranges easily.You can provide a starting value to
sum to begin adding from that number.Use a block with
sum to customize what gets added for each element.Calling
sum on non-numeric arrays without a block causes errors.The
sum method is available in Ruby 2.4 and later versions.