Skip to content

Keep the Smaller or Larger Value

Return the smaller or larger of two comparable values so callers can keep a running minimum or maximum without writing the comparison themselves.

Language: Ruby

Added on: 18th August 2026

def keep_min(left, right)
  (left <=> right) <= 0 ? left : right
end

def keep_max(left, right)
  (left <=> right) >= 0 ? left : right
end