find the average of all values in a map in ruby

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.rb
map = {a: 1, b: 2, c: 3, d: 4}
average = map.values.reduce(:+) / map.size.to_f
puts "The average value is #{average}"
118 chars
4 lines

This will output:

main.rb
The average value is 2.5
25 chars
2 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.

related categories

gistlibby LogSnag