我需要编写一个循环来执行以下操作:
if i (1..10)
do thing 1
elsif i (11..20)
do thing 2
elsif i (21..30)
do thing 3
etc...
但到目前为止,在语法方面已经走错了路。
我需要编写一个循环来执行以下操作:
if i (1..10)
do thing 1
elsif i (11..20)
do thing 2
elsif i (21..30)
do thing 3
etc...
但到目前为止,在语法方面已经走错了路。
如果 i.between?(1, 10) 做一件事 elsif i.between?(11,20) 做事2 ...
使用===
运算符(或其同义词include?
)
if (1..10) === i
正如@Baldu 所说,使用 === 运算符或内部使用 === 的用例/何时:
case i
when 1..10
# do thing 1
when 11..20
# do thing 2
when 21..30
# do thing 3
etc...
如果您仍想使用范围...
def foo(x)
if (1..10).include?(x)
puts "1 to 10"
elsif (11..20).include?(x)
puts "11 to 20"
end
end
您通常可以通过以下方式获得更好的性能:
if i >= 21
# do thing 3
elsif i >= 11
# do thing 2
elsif i >= 1
# do thing 1
你可以使用
if (1..10).cover? i then thing_1
elsif (11..20).cover? i then thing_2
并且根据Fast Ruby中的这个基准测试,它比include?
不是问题的直接答案,但如果您想要与“内部”相反:
(2..5).exclude?(7)
真的
如果您需要最快的方法来做到这一点,请使用旧的比较。
require 'benchmark'
i = 5
puts Benchmark.measure { 10000000.times {(1..10).include?(i)} }
puts Benchmark.measure { 10000000.times {i.between?(1, 10)} }
puts Benchmark.measure { 10000000.times {1 <= i && i <= 10} }
在我的系统上打印:
0.959171 0.000728 0.959899 ( 0.960447)
0.919812 0.001003 0.920815 ( 0.921089)
0.340307 0.000000 0.340307 ( 0.340358)
如您所见,双重比较几乎比or方法快 3 倍!#include?
#between?
A more dynamic answer, which can be built in Ruby:
def select_f_from(collection, point)
collection.each do |cutoff, f|
if point <= cutoff
return f
end
end
return nil
end
def foo(x)
collection = [ [ 0, nil ],
[ 10, lambda { puts "doing thing 1"} ],
[ 20, lambda { puts "doing thing 2"} ],
[ 30, lambda { puts "doing thing 3"} ],
[ 40, nil ] ]
f = select_f_from(collection, x)
f.call if f
end
So, in this case, the "ranges" are really just fenced in with nils in order to catch the boundary conditions.
对于字符串:
(["GRACE", "WEEKLY", "DAILY5"]).include?("GRACE")
#=>真