确定变量是否在范围内?

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 
...

  • 它包容性还是排他性? (4认同)
  • 这也适用于`Date`和`DateTime`对象,而`===`则不适用. (3认同)
  • @andrewcockerham 包容性。`3.between?(1, 3) => true` (2认同)

Bal*_*ldu 83

使用===运算符(或其同义词include?)

if (1..10) === i
Run Code Online (Sandbox Code Playgroud)

  • 对于未来的读者,替代方式`如果我===(1..10)`将不起作用 (6认同)
  • 如果范围非常大,似乎不是一个非常有效的解决方案. (4认同)

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)

  • 我认为这应该是明显的答案. (6认同)

Bra*_*rth 7

通常可以通过以下方式获得更好的性能:

if i >= 21
  # do thing 3
elsif i >= 11
  # do thing 2
elsif i >= 1
  # do thing 1
Run Code Online (Sandbox Code Playgroud)


Jua*_*uez 7

你可以用
if (1..10).cover? i then thing_1 elsif (11..20).cover? i then thing_2

并根据这个基准在快速红宝石比快include?


Iva*_*sky 6

如果您需要最快的方法,请使用传统的比较方法。

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?


Fel*_*ger 5

不是问题的直接答案,但如果你想要与"内"相反:

(2..5).exclude?(7)
Run Code Online (Sandbox Code Playgroud)

真正