find the average of all elements in an array in ruby

To find the average of all elements in an array in Ruby, you can sum up all the elements in the array and divide by the number of elements. Here's an example:

main.rb
array = [1, 3, 5, 7, 9]

sum = array.reduce(:+)
# sum is now 25

count = array.length
# count is now 5

average = sum.to_f / count
# average is now 5.0

puts average
# output: 5.0
180 chars
14 lines

We first define an array with some elements. Then we use the reduce method to sum all the elements in the array. We also use the length method to count the number of elements in the array. We then calculate the average by dividing the sum by the count. The to_f method is used to convert the sum to a floating point number, which is required for accurate division. Finally, we output the average using puts.

gistlibby LogSnag