Is there a built-in way or a more elegant way of restricting a number num to upper/lower bounds in Ruby or in Rails?
e.g. something like:
def number_bounded (num, lower_bound, upper_bound)
return lower_bound if num < lower_bound
return upper_bound if num > upper_bound
num
end
Here's a clever way to do it:
[lower_bound, num, upper_bound].sort[1]
But that's not very readable. If you only need to do it once, I would just do
num < lower_bound ? lower_bound : (num > upper_bound ? upper_bound : num)
or if you need it multiple times, monkey-patch the Comparable module:
module Comparable
def bound(range)
return range.first if self < range.first
return range.last if self > range.last
self
end
end
so you can use it like
num.bound(lower_bound..upper_bound)
You could also just require ruby facets, which adds a method clip
that does just this.
You can use min and max to make the code more concise:
number_bounded = [lower_bound, [upper_bound, num].min].max
class Range
def clip(n)
if cover?(n)
n
elsif n < min
min
else
max
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With