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.

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

Clamping strings

Similarly, strings can also be clamped within a range.

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

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

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.