Paul Groves Paul Groves - 11 months ago 60
Ruby Question

Array include any value from another array?

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

Answer Source
(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 comments, & works faster than any? + include?.