How to find the median among three given numbers in Ruby

1 Answer

0 votes
# Compute the median of three numbers.
# The median is the value that is neither the smallest nor the largest.
# This approach keeps the logic compact and easy to follow.
def median_of_three_numbers(a, b, c)
  # Ruby's built-in min/max handle multiple arguments cleanly.
  smallest = [a, b, c].min
  largest  = [a, b, c].max

  # The median is the one that is not equal to smallest or largest.
  # This avoids extra branching and keeps the intent clear.
  return a if a != smallest && a != largest
  return b if b != smallest && b != largest
  c         # If neither a nor b is the median, c must be.
end

# Test cases 
tests = [
  [1, 1, 1],
  [10, 3, 7],
  [10, -10, -10],
  [3, 3, 5]
]

tests.each do |(x, y, z)|
  result = median_of_three_numbers(x, y, z)
  puts "The median of [#{x}, #{y}, #{z}] is #{result}"
end



=begin
run:

The median of [1, 1, 1] is 1
The median of [10, 3, 7] is 7
The median of [10, -10, -10] is -10
The median of [3, 3, 5] is 5

=end

 



answered Aug 13 by avibootz
...