find the variance of all values in a map in ruby

To find the variance of all values in a map in Ruby, you can use the following code:

main.rb
map = {a: 5, b: 3, c: 9, d: 7}

mean = map.values.sum / map.length.to_f
variance = map.values.inject(0) { |sum, value| sum + (value - mean) ** 2 } / map.length

puts variance
175 chars
7 lines

Here, we first define a map with some sample values. We then calculate the mean of all the values in the map by summing them up and dividing by the length of the map.

Next, we use the formula for variance which is the sum of squares of differences between each value and the mean, divided by the length of the map. We use the inject method to iterate over all the values in the map and apply this formula.

Finally, we print out the calculated variance. This will give you the variance of all the values in the map.

gistlibby LogSnag