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:
To add all the values of the above array, start by defining a sum variable and initializing it to 0
Next, create a loop to iterate each element and add it to the sum variable as:
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:
sum = 0
ages.each do |i|
sum += i
end
puts sum
The resulting value is the sum of all values in the array:
Sum method
On the newer version of Ruby, you can use the sum method to add all the elements in an array.
For example:
puts ages.sum
Inject method
Ruby has a method called inject. It takes each element in an enumerator and accumulates it sequentially.
For example:
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.
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.map(&:to_i)
Once we have all the elements from the array, we can call the reduce method as:
The above syntax should return the sum of all elements in the array.
puts ages.map(&:to_i).reduce(:+)
Conclusion
This guide has illustrated various ways to add all elements in an array.