How to Find the Average Value of a Ruby Array

09/23/2021
Contents
In this article, you will learn how to find the average value of a Ruby array.
Finding the average value of a Ruby array
To find the average value of a Ruby array, you can follow these steps:
- Initialize a variable sum to 0.
- Loop through each element in the array and add it to sum.
- Divide sum by the length of the array to get the average.
- Return the average value.
Here’s the code:
def average(array)
sum = 0
array.each do |element|
sum += element
end
average = sum.to_f / array.length
return average
end
Let’s break down this code:
- The average method takes an array as an argument.
- We initialize the variable sum to 0.
- We loop through each element in the array using the each method and add it to sum.
- After the loop, we calculate the average by dividing sum by the length of the array. We use the to_f method to ensure that the result is a float.
- Finally, we return the average value.
You can call this method with any Ruby array to get its average value. For example:
array = [1, 2, 3, 4, 5]
average = average(array)
puts "The average value of the array is #{average}"
This will output:
The average value of the array is 3.0