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.