You can find the average of all values in a map (or hash in Ruby) by using the reduce
method to sum up all the values and then divide by the total number of values in the map.
Here's an example implementation:
main.rb118 chars4 lines
This will output:
main.rb25 chars2 lines
Here, we first define a map with some key-value pairs, and then we use the values
method to get an array of all the values in the map. We then call reduce
on this array, which takes a block that sums up all the values using the +
operator. The resulting sum is then divided by the size of the map (converted to a float), giving us the average. Finally, we print out the average using a string interpolation.
gistlibby LogSnag