find the median of a list of numbers in ruby

To find the median of a list of numbers in Ruby, you can perform the following steps:

  1. Sort the list of numbers in ascending order.
  2. Check if the list has an odd or even number of elements:
    • If the list has an odd number of elements, the median is the middle element.
    • If the list has an even number of elements, the median is the average of the middle two elements.
  3. Return the median value.

Here's the code that implements this algorithm:

main.rb
def median(numbers)
  sorted = numbers.sort
  size = sorted.size
  if size.odd?
    sorted[size / 2]
  else
    (sorted[size / 2 - 1] + sorted[size / 2]) / 2.0
  end
end
170 chars
10 lines

You can use this method by passing in an array of numbers:

main.rb
numbers = [1, 2, 3, 4, 5]
puts median(numbers) # Output: 3

numbers = [1, 2, 3, 4, 5, 6]
puts median(numbers) # Output: 3.5
124 chars
6 lines

related categories

gistlibby LogSnag