0

I add a method to Numeric class like this:

class Numeric
  def limitate(min, max)
    return self if self.between?(min,max)
    return max if self > max
    min
  end
end

I want to get a value if the value is in a specified range, and if it is outside range it should return maximum or minimum value.

Can I write it more simply? And how?

Stefan
  • 109,145
  • 14
  • 143
  • 218
ironsand
  • 14,329
  • 17
  • 83
  • 176

2 Answers2

2

There is sadly no clamp in Ruby yet I think. Another way to write it is:

v = [[v, min].max, max].min
BroiSatse
  • 44,031
  • 8
  • 61
  • 86
Mike Tunnicliffe
  • 10,674
  • 3
  • 31
  • 46
0

Maybe make sure that min is lower than max first.
Otherwise your method will semanticly error if the user forgot which one should go first, min or max.

min, max = max, min if min > max
Adrian
  • 425
  • 4
  • 13