How to Find Sum of Array in Ruby: Simple Guide
In Ruby, you can find the sum of an array using the
sum method directly on the array, like array.sum. This method adds all the numbers in the array and returns the total as a single number.Syntax
The basic syntax to find the sum of an array in Ruby is:
array.sum: Calls thesummethod on the array to add all its elements.
This method works on arrays containing numbers and returns their total sum.
ruby
array = [1, 2, 3, 4, 5] total = array.sum
Example
This example shows how to create an array of numbers and find their sum using the sum method.
ruby
numbers = [10, 20, 30, 40] result = numbers.sum puts result
Output
100
Common Pitfalls
Some common mistakes when summing arrays in Ruby include:
- Trying to sum arrays with non-numeric elements without handling them first.
- Using older Ruby versions where
summight not be available (before Ruby 2.4). - Confusing
sumwithinjectorreducemethods, which are more flexible but require more code.
Here is a wrong and right way example:
ruby
# Wrong: summing array with strings causes error # array = [1, 'two', 3] # puts array.sum # Right: filter numbers before summing array = [1, 'two', 3] numbers_only = array.select { |e| e.is_a?(Numeric) } puts numbers_only.sum
Output
4
Quick Reference
| Method | Description | Example |
|---|---|---|
| sum | Adds all elements in the array | [1, 2, 3].sum #=> 6 |
| inject(:+) | Adds elements using a block or symbol | [1, 2, 3].inject(:+) #=> 6 |
| reduce(:+) | Alias for inject, adds elements | [1, 2, 3].reduce(:+) #=> 6 |
Key Takeaways
Use
array.sum to quickly find the total of numeric arrays in Ruby.Ensure all elements are numbers to avoid errors when summing.
For Ruby versions before 2.4, use
inject(:+) or reduce(:+) as alternatives.Filtering non-numeric elements before summing prevents runtime errors.
The
sum method is simple and readable for beginners.