在Ruby中,如果字符串不在選項數組中,我將如何返回true?在Ruby中,如何查找字符串是否不在數組中?
# pseudo code
do_this if current_subdomain not_in ["www", "blog", "foo", "bar"]
...或者您是否知道更好的書寫方式?
在Ruby中,如果字符串不在選項數組中,我將如何返回true?在Ruby中,如何查找字符串是否不在數組中?
# 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成語。
'do_this if ![「www」,「blog」,「foo」,「bar」] .include(current_subdomain)'作品。對於複雜的條件,例如:'&&!'示例二:'而不是'。 – 2014-03-03 07:23:37
do this if not ["www", "blog", "foo", "bar"].include?(current_subdomain)
,或者您可以使用grep
>> d=["www", "blog", "foo", "bar"]
>> d.grep(/^foo$/)
=> ["foo"]
>> d.grep(/abc/)
=> []
除了使用數組,你也可以這樣做:
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)
在'answer2'中,定義數組''「www」,「blog」,「foo」,「bar」]作爲常量外的常量比使用'when'時更快。 – cbliard 2017-04-26 13:54:14
你可以試試exclude?
方法,而不是include?
例子:
do_this if ["www", "blog", "foo", "bar"].exclude?(current_subdomain)
希望這有助於...謝謝
排除?只來自ActiveSupport庫。在覈心Ruby中沒有官方支持。 – mhd 2017-05-31 05:34:09
的可能重複[測試變量是否匹配任何有若干字符串組成的W/O長IF-ELSIF鏈,或情況當[時]](http://stackoverflow.com/questions/4893816/test-if-variable-matches-any-of-several-strings-wo-long-if-elsif-chain-or-case) – 2011-04-16 05:16:27