Is there a method to limit/clamp a number?

mb14 picture mb14 · Aug 18, 2012 · Viewed 9.3k times · Source

I wrote the following code, which keeps x within the range (a..b). In pseudo code:

(if x < a, x = a; if x > b, x = b)

In Ruby it would be something like:

x = [a, [x, b].min].max

As it is quite basic and useful function, I was wondering if there is a native method to do that in ruby.

As of Ruby 2.3.3 there is apparently no method like this, what would be the shortest/more readable way to do it?

I found:

x = [a, x, b].sort[1]

so far, but I'm not sure if it is more readable.

Answer

Marc-Andr&#233; Lafortune picture Marc-André Lafortune · Aug 19, 2012

Ruby 2.4.0 introduces Comparable#clamp:

523.clamp(0, 100)        #=> 100