Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Comparable#clamp

obj.clamp(min, max) → obj
obj.clamp(range) → obj

In (min, max) form, returns min if obj <=> min is less than zero, max if obj <=> max is greater than zero, and obj otherwise.

Example
12.clamp(0, 100)         #=> 12
523.clamp(0, 100)        #=> 100
-3.123.clamp(0, 100)     #=> 0

'd'.clamp('a', 'f')      #=> 'd'
'z'.clamp('a', 'f')      #=> 'f'

In (range) form, returns range.begin if obj <=> range.begin is less than zero, range.end if obj <=> range.end is greater than zero, and obj otherwise.

Example
12.clamp(0..100)         #=> 12
523.clamp(0..100)        #=> 100
-3.123.clamp(0..100)     #=> 0

'd'.clamp('a'..'f')      #=> 'd'
'z'.clamp('a'..'f')      #=> 'f'

If range.begin is nil, it is considered smaller than obj, and if range.end is nil, it is considered greater than obj.

Example
-20.clamp(0..)           #=> 0
523.clamp(..100)         #=> 100

When range.end is excluded and not nil, an exception is raised.

Example
100.clamp(0...100)       # ArgumentError
See also #between? #>= also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0