Ruby

Ruby Array Sum

In this guide, we will discuss various techniques to sum the elements in a Ruby array.

Loop

The simplest and most common way to add elements to an array is to use a loop. We start by defining a variable to store the sum of values and initialize it to 0. Next, we iterate over each element in the array and add them to the sum variable.

Take the example array shown below:

ages = [10, 87, 34, 23, 54, 44, 23, 11, 5]

To add all the values of the above array, start by defining a sum variable and initializing it to 0

sum = 0

Next, create a loop to iterate each element and add it to the sum variable as:

ages = [10, 87, 34, 23, 54, 44, 23, 11, 5]

sum = 0

for i in ages

    sum += i

end

puts sum

Once you run the above code, you should get the sum of all the elements in the above array.

Each method

Ruby has a default method for iterating over items in an array. It accepts a block that we can use to calculate the sum of all elements.

The method works similarly to a for loop shown above.
For example:

ages = [10, 87, 34, 23, 54, 44, 23, 11, 5]

sum = 0

ages.each do |i|

    sum += i

end

puts sum

The resulting value is the sum of all values in the array:

=>291

Sum method

On the newer version of Ruby, you can use the sum method to add all the elements in an array.

For example:

ages = [10, 87, 34, 23, 54, 44, 23, 11, 5]

puts ages.sum

Inject method

Ruby has a method called inject. It takes each element in an enumerator and accumulates it sequentially.

For example:

ages = [10, 87, 34, 23, 54, 44, 23, 11, 5]

puts ages.inject(:+)

The inject method takes the first element in the array and treats it as the initial sum value. The method continues to iterate all the elements in the array, adding each of them together.

Once the method reaches the end of the array, it treats the final value as the total sum of the array.

You can also define a default value for the inject method. Take the example below that defines a default value.

ages = [10, 87, 34, 23, 54, 44, 23, 11, 5]

puts ages.inject(0) {|sum, i| sum + i}

Reduce method

The reduce method is very similar to the inject method—they are like aliases. In our example, we will use the map method to return individual elements in the array as integers.

ages = [10, 87, 34, 23, 54, 44, 23, 11, 5]

ages.map(&:to_i)

Once we have all the elements from the array, we can call the reduce method as:

reduce(:+)

The above syntax should return the sum of all elements in the array.

ages = [10, 87, 34, 23, 54, 44, 23, 11, 5]

puts ages.map(&:to_i).reduce(:+)

Conclusion

This guide has illustrated various ways to add all elements in an array.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list