Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method to limit/clamp a number?

Tags:

ruby

clamp

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.

like image 245
mb14 Avatar asked Aug 18 '12 17:08

mb14


2 Answers

Ruby 2.4.0 introduces Comparable#clamp:

523.clamp(0, 100)        #=> 100
like image 99
Marc-André Lafortune Avatar answered Oct 25 '22 12:10

Marc-André Lafortune


My own answer : NO

However

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

Is a solution.

like image 37
mb14 Avatar answered Oct 25 '22 12:10

mb14