xxra5w
Last Updated: February 25, 2016
·
1.439K
· burke

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!)

2 Responses
Add your response

5328

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

@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 ·