How to Calculate the Median of an Array of Numbers in Ruby?

You can calculate the median of an array of numbers in Ruby in the following steps:

  1. Sort the array in ascending order;
  2. Determine the median, which would be one of the following:
    1. Element at the middle index if the array has an odd number of elements, or;
    2. Average of the two elements at the middle indexes if the array has an even number of elements.

For example, you can implement this in the following way:

def median(arr)
  return nil if arr.empty?
  # 1: sort array in ascending order
  sorted_arr = arr.sort
  mid_index = sorted_arr.length / 2
  # 2.1: if odd, return middle element
  return sorted_arr[mid_index.floor].to_f if sorted_arr.length.odd?
  # 2.2: if even, return average of two middle elements
  return (sorted_arr[mid_index - 1] + sorted_arr[mid_index]).fdiv(2)
end

print median([1, 2]) #=> 1.5
print median([4, 1, 7]) #=> 4.0
print median([3, 7, 5, 1, 8, 9]) #=> 6.0
print median([39, 3, 14, 29, 23, 13, 23, 23, 40, 23, 21, 5, 7, 12, 56]) #=> 23.0

For arrays with an odd length, rounding down the middle index (i.e. mid_index.floor is needed because dividing an odd array length by 2 would result in a fraction.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.