RJHollins wrote:ah ... nice.
Interesting regarding the 'Clamp' concept.
I've been using something like this example. Restrict to values: 1 to 12
where x is Input values.
The SORT concept is something I need to play with/understand.
First question on it. What does the [1] identify ? [.sort[1]]
Yes, using min and max is what I would call the common way. First get the smaller of x and max_value then get the larger of that and min_value. That's also, how I would prefer to do it in green.
Another way would be to work with conditionals.
Code: Select all
def clamp(x, min_value, max_value)
if x < min_value
return min_value
elsif x > max_value
return max_value
else
return x
end
result = clamp(3, 5, 20) #returns 5
The array sorting method however is so elegant and instinctively understandable. Layout is "left boundary, value, right boundary", which is easy to grasp. What happens is that an array is filled with these three values, then sorted and then the middle value from the array is returned [1] <- index starts at 0, so 1 is the second value.
If you use some numbers it becomes apparent:
[1, 5, 12].sort[1] -> after sort it's still [1, 5, 12] -> middle value is returned -> 5
[1, 0, 12].sort[1] -> after sort it's [0, 1, 12] -> middle value is returned -> 1
[1, 13, 12].sort[1] -> after sort it's [1, 12, 13] -> middle value is returned -> 12