find the average of a list of numbers in ruby

To find the average of a list of numbers in ruby, you can use the built-in reduce method and divide the sum by the length of the array:

main.rb
numbers = [1, 2, 3, 4, 5]
average = numbers.reduce(:+) / numbers.length.to_f
puts "The average is: #{average}"
111 chars
4 lines

The reduce method adds up all the elements in the array by calling the + method on each element. The to_f method converts the length to a float, so that the result of the division will be a float.

related categories

gistlibby LogSnag