Ruby 2.4 adds Comparable#clamp method

Abhishek Jain

By Abhishek Jain

on December 13, 2016

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.

210.clamp(5, 20)
3=> 10
510.clamp(15, 20)
6=> 15
810.clamp(0, 5)
9=> 5

Clamping strings

Similarly, strings can also be clamped within a range.

2"e".clamp("a", "s")
3=> "e"
5"e".clamp("f", "s")
6=> "f"
8"e".clamp("a", "c")
9=> "c"
11"this".clamp("thief", "thin")
12=> "thin"

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

1if x <=> min < 0, x = min;
2if x <=> max > 0 , x = max
3else x

Stay up to date with our blogs. Sign up for our newsletter.

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