Search⌘ K
AI Features

Solution: Find the Median

Understand how to find the median in Ruby arrays by transforming string inputs into integers, sorting the data, and applying logic for both even and odd length arrays. This lesson guides you through practical steps to compute medians using Ruby's core methods.

We'll cover the following...

Calculating the median

the_median = nil
print "Enter a list of numbers (separated by space): "
input = gets.chomp
array = input.split.collect{ |x| x.to_i }.sort
length = array.length
mid = length / 2
if length.even?
    the_median = (array[mid - 1] + array[mid]) / 2.0
else
    the_median = array[mid] 
end
puts the_median
Find the median of an array

Explanation

  • Line 3: The ...