Is there a method to limit/clamp a number?
问题 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. 回答1: Ruby 2.4.0