To find the variance of a list of numbers in Ruby, we can use the Enumerable#reduce method to first calculate the mean of the list, then use another iteration to calculate the sum of the squared differences from the mean, and finally divide by the length of the list minus 1 to get the variance:
main.rb231 chars8 lines
Here we use the reduce
method twice: the first time to compute the sum of the numbers in the list using the :+
operator (which is equivalent to x-y
), and the second time to compute the sum of squared differences from the mean of the list using a block that takes two arguments: the accumulator (acc
) and the current element (x
), and returns the new accumulator value.
Finally, we divide the sum_sq_diff
by (n - 1).to_f
to get the unbiased sample variance (the correction factor of n-1
instead of n
accounts for the fact that the sample mean is used instead of the true mean of the population).
We should note that the above implementation assumes that the input list contains only numeric values. If the list could contain non-numeric or nil elements, we should add appropriate type checks to avoid type-related errors.
gistlibby LogSnag