Is there a method to limit/clamp a number?

后端 未结 5 715
醉酒成梦
醉酒成梦 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: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

提交回复
热议问题