有没有限制/限制数字的方法? [英] Is there a method to limit/clamp a number?
本文介绍了有没有限制/限制数字的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了以下代码,将x
保持在(a..b)
范围内.用伪代码:
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)
在Ruby中,它类似于:
In Ruby it would be something like:
x = [a, [x, b].min].max
因为它是非常基本且有用的功能,所以我想知道在ruby中是否有本机方法可以做到这一点.
As it is quite basic and useful function, I was wondering if there is a native method to do that in ruby.
从Ruby 2.3.3开始,显然没有这样的方法,最短/更易读的方法是什么?
As of Ruby 2.3.3 there is apparently no method like this, what would be the shortest/more readable way to do it?
我发现:
x = [a, x, b].sort[1]
到目前为止,但是我不确定它是否更具可读性.
so far, but I'm not sure if it is more readable.
推荐答案
Ruby 2.4.0 introduces Comparable#clamp
:
523.clamp(0, 100) #=> 100
这篇关于有没有限制/限制数字的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文