次のようなループを作成する必要があります。
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...
しかし、これまでのところ、構文に関して間違った道を進んでいます。
if i. between?(1, 10) ことをする 1 elsif i. between?(11,20) ことをする 2 ...
===
演算子 (またはその同義語include?
)を使用する
if (1..10) === i
@Baldu が言ったように、 === 演算子または use case/when を内部的に使用する === を使用します。
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
質問への直接の答えではありませんが、「内」の反対が必要な場合:
(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?
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
したがって、この場合、「範囲」は実際には、境界条件をキャッチするために nil で囲まれています。
文字列の場合:
(["GRACE", "WEEKLY", "DAILY5"]).include?("GRACE")
#=> true