繁体   English   中英

在 Ruby 中,如何确定字符串是否不在数组中?

[英]In Ruby, how do I find out if a string is not in an array?

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

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

……或者你知道写这个更好的方法吗?

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

或者

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

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

然而,使用unless是一个相当大的ruby 习语。

你可以试试exclude? 方法而不是include?

例子:

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

希望这有助于...谢谢

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

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)
do this if not ["www", "blog", "foo", "bar"].include?(current_subdomain)

或者你可以使用grep

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM