find the average of all keys in a map in ruby

You can use the reduce method to calculate the sum of all the keys in the map, then divide by the number of keys to find the average:

main.rb
map = { 'a' => 1, 'b' => 2, 'c' => 3 }
average = map.keys.reduce(0.0) { |sum, key| sum + key.to_f } / map.length
puts average # Output: 1.5
140 chars
4 lines

Here, we first initialize average to 0.0, because we want to ensure that the final result is a float. Then, we call reduce on the keys of the map, passing in 0.0 as the initial value of the sum accumulator. We then add each key to the sum accumulator (converting the key to a float, because the keys are strings), and finally divide by the number of keys in the map to get the average.

related categories

gistlibby LogSnag