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

前端 未结 5 1807
北荒
北荒 2021-01-01 08:44

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\", \"         


        
相关标签:
5条回答
  • 2021-01-01 09:25

    You can try exclude? method instead of include?

    Example:

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

    Hope this help...Thanks

    0 讨论(0)
  • 2021-01-01 09:25

    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)
    
    0 讨论(0)
  • 2021-01-01 09:34
    do this if not ["www", "blog", "foo", "bar"].include?(current_subdomain)
    

    or you can use grep

    >> d=["www", "blog", "foo", "bar"]
    >> d.grep(/^foo$/)
    => ["foo"]
    >> d.grep(/abc/)
    => []
    
    0 讨论(0)
  • 2021-01-01 09:34

    I find this approach most readable !'foo'.in?(['bar', 'baz'])

    0 讨论(0)
  • 2021-01-01 09:43
    do_this unless  ["www", "blog", "foo", "bar"].include?(current_subdomain)
    

    or

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

    I'm using the Array#include? method.

    However using unless is a fairly big ruby idiom.

    0 讨论(0)
提交回复
热议问题