How can I write a Ruby function that can calculate the average of an array? If the array doesn't have any elements, the result should be 0. I should use a loop for the implementation. I started like this, but I'm not quite sure how to use the loop.
a = [1, 2, 3, 4, 5, 6]
def average(a)
sum = 0.0
result = 0.0
if array.length > 0 then
array.each do |item|
sum += item
end
result = sum / array.length
end
return result.to_f
end