Skip to content

Instantly share code, notes, and snippets.

@mudge
Created July 29, 2008 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mudge/3061 to your computer and use it in GitHub Desktop.
Save mudge/3061 to your computer and use it in GitHub Desktop.
Methods to calculate the mean, median and mode of an array.
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