There are many ways to calculate the sum of an array of numbers in Ruby. The easiest way is by using the sum method.

nums_array = [1,2,3,4,5,6,7]

print nums_array.sum

#Output:
28

This is definitely the easiest way if dealing with a simple array of numbers. There are a bunch of other ways to sum an array, so let’s take a look at a couple of other options.


We can use the each method to traverse the array and easily sum up all of its numbers.

nums_array = [1,2,3,4,5,6,7]

sum = 0

nums_array.each do |num|
  sum += num
end

print sum

#Output:
28

We can also use the reduce method to sum an array using a little less code than the each method.

nums_array = [1,2,3,4,5,6,7]

print nums_array.reduce { |sum, num| sum + num }

#Output:
28

Finally, let’s look at using a for loop to sum the numbers of an array.

nums_array = [1,2,3,4,5,6,7]

sum = 0

for num in nums_array
  sum += num
end

print sum

#Output:
28

When working with collections of data in Ruby, the ability to summarize the data easily is valuable. One such case is if you want to get the sum of an array of numbers. To calculate the sum of an array of numbers in Ruby, the easiest way is with the sum method. sum returns the sum of an array of numbers.

Below again, is the easiest way to get the sum of an array of numbers in Ruby using the sum method.

nums_array = [-91,12,37,14,-45,65,7]

print nums_array.sum

#Output:
-1

Hopefully this article has been useful for you to learn how to sum an array in Ruby.

Categorized in:

Ruby,

Last Update: March 1, 2024