find the standard deviation of all values in a map in ruby

To find the standard deviation of all values in a map in Ruby, we'll need to do a bit of math. Here's the code:

main.rb
require 'mathn'

def standard_deviation(map)
  # calculate the mean (average)
  mean = map.values.reduce(&:+) / map.size.to_f

  # calculate the sum of the squared differences from the mean
  sum_of_squared_differences = map.values.reduce(0) { |sum, value| sum += (value - mean) ** 2 }

  # calculate the variance
  variance = sum_of_squared_differences / map.size

  # calculate the standard deviation by taking the square root of the variance
  standard_deviation = Math.sqrt(variance)

  return standard_deviation
end
521 chars
18 lines

This code defines a method, standard_deviation, that takes a map as an argument, calculates the mean (average) of all the values in the map, then calculates the sum of the squared differences from the mean, the variance and the standard deviation of the map's values. The method returns the standard deviation.

We start by requiring the mathn library, which Ruby uses for math calculations. We then define our standard_deviation method.

To calculate the mean, we use reduce to add up all the values in the map, then divide the result by the size of the map, converted to a float.

To calculate the sum of the squared differences from the mean, we use another call to reduce, starting with 0 as the initial value. For each value in the map, we add the squared difference between the value and the mean.

Once we have the sum of the squared differences, we divide by the size of the map to get the variance.

Finally, we take the square root of the variance to get the standard deviation, and return it from the method.

gistlibby LogSnag