Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Comparable#clamp

[A, B] (A min, B max) -> (self | A | B)
[A] (::Range[A]) -> (self | A)
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'

If min is nil, it is considered smaller than obj, and if max is nil, it is considered greater than obj.

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

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.3 · 3.2 · 3.1 · 3.0