In Ruby, how would I return true if a string is not in an array of options?
# pseudo code
do_this if current_subdomain not_in [\"www\", \"blog\", \"foo\", \"
Besides using an array, you can also do this:
case current_subdomain
when 'www', 'blog', 'foo', 'bar'; do that
else do this
end
This is actually much faster:
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)