mb14 mb14 - 3 months ago 6
Ruby Question

Is there a limit/clamp function in ruby

I wrote the following code, which keeps

x
within the range
[a,b]
(if
x
<
a
,
x
=
a
; if
x
>
b
,
x
=
b
):

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


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

Update
As there is apparently no method to do it, what would be the shortest/more readable way to do it? I found

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


so far, but am not sure if it is more readable.

Answer

Ruby 2.4.0 will introduce Comparable#clamp:

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