Method: Numeric#clamp

Defined in:
lib/mug/clamp.rb

#clamp(lower, higher = nil) ⇒ Object

Clamps num so that lower <= new_num <= higher.

Returns lower when num < lower, higher when num > higher, otherwise num itself.

Raises an exception if lower > higher

Raises:

  • (ArgumentError)


12
13
14
15
16
# File 'lib/mug/clamp.rb', line 12

def clamp lower, higher=nil
  return lower.bound(self) if lower.is_a?(Range) && higher.nil?
  raise ArgumentError, 'range must not be negative' if lower > higher
  [[lower, self].max, higher].min
end