BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Ruby 2.4 adds Comparable#clamp method

This blog is part of our Ruby 2.4 series.

In Ruby 2.4, clamp method is added to the Comparable module. This method can be used to clamp an object within a specific range of values.

clamp method takes min and max as two arguments to define the range of values in which the given argument should be clamped.

Clamping numbers

clamp can be used to keep a number within the range of min, max.

10.clamp(5, 20)
=> 10

10.clamp(15, 20)
=> 15

10.clamp(0, 5)
=> 5

Clamping strings

Similarly, strings can also be clamped within a range.

"e".clamp("a", "s")
=> "e"

"e".clamp("f", "s")
=> "f"

"e".clamp("a", "c")
=> "c"

"this".clamp("thief", "thin")
=> "thin"

Internally, this method relies on applying the spaceship <=> operator between the object and the min & max arguments.

if x <=> min < 0, x = min;
if x <=> max > 0 , x = max
else x
Abhishek Jain in Ruby 2.4
13, 2016

You might also like

Ruby 2.4 has optimized enumerable min max methods

CSV::Row#each etc. return enumerator when no block given

Ruby 2.4 DateTime#to_time & Time#to_time keeps info

Avoid exception for dup on Integer

Ruby 2.4 no exception for objects converted to IPAddr

Subscribe to our newsletter