142

我需要编写一个循环来执行以下操作:

if i (1..10)
  do thing 1
elsif i (11..20)
  do thing 2
elsif i (21..30)
  do thing 3
etc...

但到目前为止,在语法方面已经走错了路。

4

10 回答 10

319
如果 i.between?(1, 10)
  做一件事
elsif i.between?(11,20)
  做事2
...
于 2010-08-17T19:01:21.377 回答
91

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

if (1..10) === i
于 2009-05-15T19:52:18.977 回答
71

正如@Baldu 所说,使用 === 运算符或内部使用 === 的用例/何时:

case i
when 1..10
  # do thing 1
when 11..20
  # do thing 2
when 21..30
  # do thing 3
etc...
于 2009-05-15T19:55:16.287 回答
42

如果您仍想使用范围...

def foo(x)
 if (1..10).include?(x)
   puts "1 to 10"
 elsif (11..20).include?(x)
   puts "11 to 20"
 end
end
于 2009-05-15T19:54:45.477 回答
9

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

if i >= 21
  # do thing 3
elsif i >= 11
  # do thing 2
elsif i >= 1
  # do thing 1
于 2014-05-28T21:15:03.803 回答
9

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

并且根据Fast Ruby中的这个基准测试,它比include?

于 2017-08-28T15:54:25.387 回答
6

不是问题的直接答案,但如果您想要与“内部”相反:

(2..5).exclude?(7)

真的

于 2016-11-09T14:05:55.313 回答
2

如果您需要最快的方法来做到这一点,请使用旧的比较。

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?

于 2021-05-19T00:43:02.830 回答
1

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.

于 2009-05-16T04:58:29.960 回答
-2

对于字符串:

(["GRACE", "WEEKLY", "DAILY5"]).include?("GRACE")

#=>真

于 2012-12-14T11:39:28.317 回答