OneBite.Dev - Coding blog in a bite size

find the average of all elements in an array in Ruby

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

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

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

average = sum.to_f / array.length

This code finds the average of all elements in an array. First, the array is initialized with five elements. Then a variable, sum, is initialized with a value of 0. Next, the each method is used to loop through each element in the array. For each element, the value of the sum variable is updated by adding the element to the value of sum. After efficiently looping through all elements, the average is calculated by dividing the new sum of all elements in the array by the length (or number of elements) in the array. Finally, the result is stored in a new variable called average. This is the average of all elements in the array.

ruby