Is there a method to limit/clamp a number?

后端 未结 5 692
醉酒成梦
醉酒成梦 2021-01-01 10:51

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)


        
相关标签:
5条回答
  • 2021-01-01 10:55

    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
    
    0 讨论(0)
  • 2021-01-01 10:56

    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.

    0 讨论(0)
  • 2021-01-01 10:58

    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
    
    0 讨论(0)
  • 2021-01-01 11:05

    My own answer : NO

    However

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

    Is a solution.

    0 讨论(0)
  • 2021-01-01 11:11

    Ruby 2.4.0 introduces Comparable#clamp:

    523.clamp(0, 100)        #=> 100
    
    0 讨论(0)
提交回复
热议问题