Created
July 29, 2008 10:49
-
-
Save mudge/3061 to your computer and use it in GitHub Desktop.
Methods to calculate the mean, median and mode of an array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Averageable | |
def mean(&block) | |
sum(&block) / length.to_f | |
end | |
def count(elem) | |
length - (self - [elem]).length | |
end | |
def mode | |
max { |a, b| count(a) <=> count(b) } | |
end | |
def median | |
sorted = sort | |
index = (length / 2) - 1 | |
if length_odd? | |
sorted[index + 1] | |
else | |
(sorted[index] + sorted[index + 1]) / 2.0 | |
end | |
end | |
def length_even? | |
(length % 2).zero? | |
end | |
def length_odd? | |
!length_even? | |
end | |
# From ActiveSupport. | |
def sum(identity = 0, &block) | |
return identity unless size > 0 | |
if block_given? | |
map(&block).sum | |
else | |
inject { |sum, element| sum + element } | |
end | |
end unless method_defined?(:sum) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment