在Ruby中,如何判断字符串是否不在数组中?

时间:2011-04-16 02:06:12

标签: ruby arrays

在Ruby中,如果字符串不在选项数组中,我将如何返回true?

# pseudo code
do_this if current_subdomain not_in ["www", "blog", "foo", "bar"]

......或者你知道一个更好的方法吗?

5 个答案:

答案 0 :(得分:53)

do_this unless  ["www", "blog", "foo", "bar"].include?(current_subdomain)

do_this if not ["www", "blog", "foo", "bar"].include?(current_subdomain)

我正在使用Array#include?方法。

然而,使用unless是一个相当大的红宝石成语。

答案 1 :(得分:5)

除了使用数组外,您还可以这样做:

case current_subdomain
when 'www', 'blog', 'foo', 'bar'; do that
else do this
end

这实际上要快得多:

require 'benchmark'
n = 1000000

def answer1 current_subdomain
  case current_subdomain
  when 'www', 'blog', 'foo', 'bar'
  else nil
  end
end

def answer2 current_subdomain
  nil unless  ["www", "blog", "foo", "bar"].include?(current_subdomain)
end

Benchmark.bmbm do |b|
  b.report('answer1'){n.times{answer1('bar')}}
  b.report('answer2'){n.times{answer2('bar')}}
end

Rehearsal -------------------------------------------
answer1   0.290000   0.000000   0.290000 (  0.286367)
answer2   1.170000   0.000000   1.170000 (  1.175492)
---------------------------------- total: 1.460000sec

              user     system      total        real
answer1   0.290000   0.000000   0.290000 (  0.282610)
answer2   1.180000   0.000000   1.180000 (  1.186130)


Benchmark.bmbm do |b|
  b.report('answer1'){n.times{answer1('hello')}}
  b.report('answer2'){n.times{answer2('hello')}}
end

Rehearsal -------------------------------------------
answer1   0.250000   0.000000   0.250000 (  0.252618)
answer2   1.100000   0.000000   1.100000 (  1.091571)
---------------------------------- total: 1.350000sec

              user     system      total        real
answer1   0.250000   0.000000   0.250000 (  0.251833)
answer2   1.090000   0.000000   1.090000 (  1.090418)

答案 2 :(得分:2)

do this if not ["www", "blog", "foo", "bar"].include?(current_subdomain)

或者您可以使用grep

>> d=["www", "blog", "foo", "bar"]
>> d.grep(/^foo$/)
=> ["foo"]
>> d.grep(/abc/)
=> []

答案 3 :(得分:2)

您可以尝试exclude?方法而不是include?

示例:

do_this if ["www", "blog", "foo", "bar"].exclude?(current_subdomain)

希望这有帮助......谢谢

答案 4 :(得分:1)

我发现这种方法最容易理解!'foo'.in?(['bar', 'baz'])