module Nuggets::Array::MedianMixin

Public Instance Methods

median([prefer]) → anObject click to toggle source
median { |left, right| ... } → anObject

Determines the median of the values in array. array must be sortable.

If array contains an even number of values, a block may be passed to decide what the “middle” (average) should be. For Numeric values, the block is optional and the arithmetic mean will be used when no block is passed; for other values, the block is mandatory.

Alternatively, prefer may either be set to true, 1, or :left to use the left “middle”, or to false, 2, or :right to use the right “middle”. The block will then be ignored.

# File lib/nuggets/array/median_mixin.rb, line 46
def median(prefer = nil)
  return if empty?

  sorted, index = sort, (size / 2.0).ceil - 1

  case prefer
    when true,  1, :left  then prefer_left  = true
    when false, 2, :right then prefer_right = true

  middle1 = sorted[index]
  return middle1 if prefer_left || size.odd?

  middle2 = sorted[index + 1]
  return middle2 if prefer_right

  unless block_given?
    # simple arithmetic mean
    (middle1 + middle2) / 2.0
    # make your own average
    yield middle1, middle2