32

I wrote the following code, which keeps x within the range (a..b). In pseudo code:

(if x < a, x = a; if x > b, x = b)

In Ruby it would be something like:

x = [a, [x, b].min].max

As it is quite basic and useful function, I was wondering if there is a native method to do that in ruby.

As of Ruby 2.3.3 there is apparently no method like this, what would be the shortest/more readable way to do it?

I found:

x = [a, x, b].sort[1]

so far, but I'm not sure if it is more readable.

Drenmi
  • 8,492
  • 4
  • 42
  • 51
mb14
  • 22,276
  • 7
  • 60
  • 102

5 Answers5

61

Ruby 2.4.0 introduces Comparable#clamp:

523.clamp(0, 100)        #=> 100
Drenmi
  • 8,492
  • 4
  • 42
  • 51
Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166
37

My own answer : NO

However

x = [a, x, b].sort[1]

Is a solution.

mb14
  • 22,276
  • 7
  • 60
  • 102
12

I did this:

class Numeric
  def clamp min, max
    [[self, max].min, min].max
  end
end

So whenever I want to clamp anything, I can just call:

x.clamp(min, max)

Which I find pretty readable.

Zeddy
  • 121
  • 2
  • 4
0

Here is my solution which borrows heavily from the actual implementation:

unless Comparable.method_defined? :clamp
  module Comparable
    def clamp min, max
      if max-min<0
        raise ArgumentError, 'min argument must be smaller than max argument'
      end
      self>max ? max : self<min ? min : self
    end
  end
end
-1

The most appealing solution for now in my opinion is the sort option:

[min,x,max].sort[1] 

When you don't mind monkey patching existing core classes. I think the range class is a good candidate for a clamp method

class Range
  def clamp(v)
    [min,v,max].sort[1]
  end
end

(min..max).clamp(v)

Or the plain array object. I don't like this, because the clamp function only is correct for 3 element arrays

class Array
    def clamp
      sort[1]
    end
end

You can call it like this:

[a,x,b].clamp
gamecreature
  • 3,232
  • 3
  • 20
  • 18
  • Calling clamp over an array or a range seems to be really deceiving. That is not a result someone would think about. Monkey patching numeric or comparable looks like something easier to understand IMHO. – Ulysse BN Aug 22 '18 at 09:43