btw*_*btw 130 ruby conditional integer range
我需要编写一个循环来执行以下操作:
if i (1..10)
do thing 1
elsif i (11..20)
do thing 2
elsif i (21..30)
do thing 3
etc...
Run Code Online (Sandbox Code Playgroud)
但到目前为止,在语法方面走错了道路.
rog*_*ack 298
if i.between?(1, 10) do thing 1 elsif i.between?(11,20) do thing 2 ...
Bal*_*ldu 83
使用===运算符(或其同义词include?)
if (1..10) === i
Run Code Online (Sandbox Code Playgroud)
Vin*_*ert 70
正如@Baldu所说,使用===运算符或用例/何时在内部使用===:
case i
when 1..10
# do thing 1
when 11..20
# do thing 2
when 21..30
# do thing 3
etc...
Run Code Online (Sandbox Code Playgroud)
Tim*_*han 40
如果你还想使用范围......
def foo(x)
if (1..10).include?(x)
puts "1 to 10"
elsif (11..20).include?(x)
puts "11 to 20"
end
end
Run Code Online (Sandbox Code Playgroud)
通常可以通过以下方式获得更好的性能:
if i >= 21
# do thing 3
elsif i >= 11
# do thing 2
elsif i >= 1
# do thing 1
Run Code Online (Sandbox Code Playgroud)
如果您需要最快的方法,请使用传统的比较方法。
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} }
Run Code Online (Sandbox Code Playgroud)
在我的系统上打印:
0.959171 0.000728 0.959899 ( 0.960447)
0.919812 0.001003 0.920815 ( 0.921089)
0.340307 0.000000 0.340307 ( 0.340358)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,双重比较几乎比or方法快 3 倍!#include?#between?
| 归档时间: |
|
| 查看次数: |
75679 次 |
| 最近记录: |