OneBite.Dev - Coding blog in a bite size

find the sum of all elements in an array in Ruby

Code snippet on how to find the sum of all elements in an array in Ruby

array = [1, 2, 3, 4, 5]
sum = 0

array.each do |number|
  sum += number
end

puts sum # output 15

This code takes an array of numbers, then sets up a variable called sum and sets it to 0. The code then loops through the array using the each method and for each number, it adds it to the value of sum. After looping through all the elements, it prints out the value of sum, which is the total of all elements in the array. In this example, the output would be 15.

ruby