在Ruby中,如何判断字符串是否不在数组中?
在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成语。
除了使用数组,您还可以这样做:
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/) => []
你可以尝试exclude?
方法而不是include?
例:
do_this if ["www", "blog", "foo", "bar"].exclude?(current_subdomain)
希望这有帮助…谢谢