Array include any value from another array?

后端 未结 5 1974
青春惊慌失措
青春惊慌失措 2020-12-12 12:23

What\'s the most efficient way to test if an array contains any element from a second array?

Two examples below, attempting to answer the question does foods

5条回答
  •  失恋的感觉
    2020-12-12 12:54

    How about Enumerable#any?

    >> cheeses = %w(chedder stilton brie mozzarella feta haloumi)
    => ["chedder", "stilton", "brie", "mozzarella", "feta", "haloumi"]
    >> foods = %w(pizza feta foods bread biscuits yoghurt bacon)
    => ["pizza", "feta", "foods", "bread", "biscuits", "yoghurt", "bacon"]
    >> foods.any? {|food| cheeses.include?(food) }
    => true
    

    Benchmark script:

    require "benchmark"
    N = 1_000_000
    puts "ruby version: #{RUBY_VERSION}"
    
    CHEESES = %w(chedder stilton brie mozzarella feta haloumi).freeze
    FOODS = %w(pizza feta foods bread biscuits yoghurt bacon).freeze
    
    Benchmark.bm(15) do |b|
      b.report("&, empty?") { N.times { (FOODS & CHEESES).empty? } }
      b.report("any?, include?") { N.times { FOODS.any? {|food| CHEESES.include?(food) } } }
    end
    

    Result:

    ruby version: 2.1.9
                          user     system      total        real
    &, empty?         1.170000   0.000000   1.170000 (  1.172507)
    any?, include?    0.660000   0.000000   0.660000 (  0.666015)
    

提交回复
热议问题