xxra5w
Last Updated: February 25, 2016
·
1.385K
· burke
582037f79cc8b997eed3c2e55980d474

Constrain a value to a range

class Range
  def bounding(val)
    [[val, first].max, last].min
  end  
end  

(0..100).bounding(88) #=> 88
(0..100).bounding(111) #=> 100
(0..100).bounding(-3) #=> 0

It's always bothered me a little bit that there's no single method to do this in the standard library (or even ActiveSupport!)

Say Thanks
Respond

2 Responses
Add your response

5328
B06d8e26b92456b228d3c77b66397534

Ranges can be exclusive... not sure (0...10).bounding(42) # => 10 makes sense.
If something bothers you... why not try to improve things? Be sure to check http://bugs.ruby-lang.org/issues/4574

over 1 year ago ·
5782
673b3af90381f26882b7e7283ab137fa

@marc-andre, you can get the correct behavior with:

class Range
  def bounding(val)
    [[val, min].max, max].min
  end  
end 

(1..9).bounding  10 #=> 9
(1...9).bounding 10 #=> 8
over 1 year ago ·