将数字限制为上限/下限?

时间:2021-10-08 11:19:38

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?

是否有内置方式或更优雅的方法将数字限制为Ruby或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

4 个解决方案

#1


13  

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.

你也可以只需要ruby facets,它会添加一个方法剪辑来实现这一点。

#2


12  

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

您可以使用min和max来使代码更简洁:

number_bounded = [lower_bound, [upper_bound, num].min].max

#3


1  

class Range

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

end

#4


0  

Since you're mentioning Rails, I'll mention how to do this with a validation.

既然你提到了Rails,我将提到如何通过验证来做到这一点。

validates_inclusion_of :the_column, :in => 5..10

That won't auto-adjust the number, of course.

当然,这不会自动调整数量。

#1


13  

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.

你也可以只需要ruby facets,它会添加一个方法剪辑来实现这一点。

#2


12  

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

您可以使用min和max来使代码更简洁:

number_bounded = [lower_bound, [upper_bound, num].min].max

#3


1  

class Range

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

end

#4


0  

Since you're mentioning Rails, I'll mention how to do this with a validation.

既然你提到了Rails,我将提到如何通过验证来做到这一点。

validates_inclusion_of :the_column, :in => 5..10

That won't auto-adjust the number, of course.

当然,这不会自动调整数量。