Calculating Median in Ruby

How do I calculate the median of an array of numbers using Ruby?

I am a beginner and am struggling with handling the cases of the array being of odd and even length.


Solution 1:

Here is a solution that works on both even and odd length array and won't alter the array:

def median(array)
  return nil if array.empty?
  sorted = array.sort
  len = sorted.length
  (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0
end

Solution 2:

Similar to nbarraille's, but I find it a bit easier to keep track of why this one works:

class Array
  def median
    sorted = self.sort
    half_len = (sorted.length / 2.0).ceil
    (sorted[half_len-1] + sorted[-half_len]) / 2.0
  end
end

half_len = number of elements up to and including (for array with odd number of items) middle of array.

Even simpler:

class Array
  def median
    sorted = self.sort
    mid = (sorted.length - 1) / 2.0
    (sorted[mid.floor] + sorted[mid.ceil]) / 2.0
  end
end