我有一个实例变量@limit,它必须大于0且不大于20.我目前有这样的代码:
@limit = (params[:limit] || 10).to_i
@limit = 20 if @limit > 20
@limit = 0 if @limit < 0
Run Code Online (Sandbox Code Playgroud)
这看起来很难看.有没有更好的方法将整数限制为一系列值?
谢谢!
Rya*_*ary 22
Comparable#clamp是用Ruby 2.4提供.3.clamp(10, 20)
=> 10
27.clamp(10, 20)
=> 20
15.clamp(10, 20)
=> 15
Run Code Online (Sandbox Code Playgroud)
fal*_*tru 18
如何使用Enumerable#min,Enumerable#max?
例如,要限制范围中的值0..10:
x = 100
[[10, x].min, 0].max
# => 10
x = -2
[[10, x].min, 0].max
# => 0
x = 5
[[10, x].min, 0].max
# => 5
Run Code Online (Sandbox Code Playgroud)
替代方案,使用Enumerable#sort:
x = 100
[x, 0, 10].sort[1]
# => 10
x = -2
[x, 0, 10].sort[1]
# => 0
x = 5
[x, 0, 10].sort[1]
# => 5
Run Code Online (Sandbox Code Playgroud)
这是一个快速基准,以显示我们应该使用哪种方法.因为有人会不可避免地说"使用sort_by因为它比它更快sort",所以我补充说.sort_by只比sort处理复杂对象时更快.基本对象,如整数和字符串应该由sort.
require 'fruity'
class Numeric
def clamp(min, max)
self < min ? min : self > max ? max : self
end
end
compare do
min_max { [[10, 100].min, 0].max }
sort { [100, 0, 10].sort[1] }
sort_by { [100, 0, 10].sort_by{ |v| v }[1] }
clamp_test { 10.clamp(0, 100) }
original {
limit = 10
limit = 100 if limit > 100
limit = 0 if limit < 0
limit
}
end
Run Code Online (Sandbox Code Playgroud)
结果如下:
Running each test 65536 times. Test will take about 8 seconds.
original is faster than clamp_test by 2x ± 1.0
clamp_test is faster than sort by 6x ± 1.0
sort is faster than min_max by 2x ± 0.1
min_max is faster than sort_by by 2x ± 0.1
Run Code Online (Sandbox Code Playgroud)
有时丑陋更好.
如果你觉得猴子修补方法,你可能会这样做:
class Numeric
def clamp(min, max)
self < min ? min : self > max ? max : self
end
end
# usage
@limit = (params[:limit] || 10).clamp(0, 20)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3829 次 |
| 最近记录: |