Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict a number to upper/lower bounds?

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
like image 950
Amy Avatar asked Jun 16 '10 17:06

Amy


3 Answers

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.

like image 85
mckeed Avatar answered Oct 20 '22 01:10

mckeed


You can use min and max to make the code more concise:

number_bounded = [lower_bound, [upper_bound, num].min].max
like image 24
Mark Byers Avatar answered Oct 19 '22 23:10

Mark Byers


class Range

  def clip(n)
    if cover?(n)
      n
    elsif n < min
      min
    else
      max
    end
  end

end
like image 42
Bill Lipa Avatar answered Oct 20 '22 01:10

Bill Lipa