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.rb521 chars18 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