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)
The most appealing solution for now in my opinion is the sort option:
[min,x,max].sort[1]
When you don't mind monkey patching existing core classes. I think the range class is a good candidate for a clamp method
class Range
def clamp(v)
[min,v,max].sort[1]
end
end
(min..max).clamp(v)
Or the plain array object. I don't like this, because the clamp function only is correct for 3 element arrays
class Array
def clamp
sort[1]
end
end
You can call it like this:
[a,x,b].clamp