tags:

views:

45

answers:

3

What's the best, most elegant/efficient way to test if an array contains any element from a second array?

Two examples below, attempting to answer the question does 'foods' contain any element from 'cheeses':

cheeses = %w(chedder stilton brie mozzarella feta haloumi)
foods = %w(pizza feta foods bread biscuits yoghurt bacon)

puts cheeses.collect{|c| foods.include?(c)}.include?(true)

puts (cheeses - foods).size < cheeses.size
+1  A: 

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
injekt
Thanks for this, will definitely remember the any? method
Paul Groves
+2  A: 
(cheeses & foods).empty?

It does the same, what posted injekt, but it's already compiled actions in a language.

As Marc-André Lafortune said in comment, & works faster, than any? + include?.

Nakilon
Great - thanks alot for this!
Paul Groves
Marc-André Lafortune
+4  A: 

You can check if the intersection is empty.

cheeses = %w(chedder stilton brie mozzarella feta haloumi)
foods = %w(pizza feta foods bread biscuits yoghurt bacon)
foods & cheeses
=> ["feta"] 
(foods & cheeses).empty?
=> false
Simone Carletti