find the standard deviation of all elements in an array in ruby

Here's a code snippet that calculates the standard deviation of all elements in an array in Ruby, by first calculating the mean of the array and then summing the squared difference of each element from the mean:

main.rb
def standard_deviation(arr)
  n = arr.length
  mean = arr.sum / n.to_f
  variance = arr.map { |x| (x - mean)**2 }.sum / n
  Math.sqrt(variance)
end
148 chars
7 lines

To use this method, simply pass in your array as an argument:

main.rb
my_array = [1, 2, 3, 4, 5]
puts standard_deviation(my_array)
61 chars
3 lines

This will output 1.5811388300841898, which is the standard deviation of the array.

gistlibby LogSnag