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.rb140 chars4 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.
gistlibby LogSnag