Find values in common between two arrays

Solution 1:

You can use the set intersection method & for that:

x = [1, 2, 4]
y = [5, 2, 4]
x & y # => [2, 4]

Solution 2:

x = [1, 2, 4]
y = [5, 2, 4]
intersection = (x & y)
num = intersection.length
puts "There are #{num} numbers common in both arrays. Numbers are #{intersection}"

Will output:

There are 2 numbers common in both arrays. Numbers are [2, 4]

Solution 3:

OK, so the & operator appears to be the only thing you need to do to get this answer.

But before I knew that I wrote a quick monkey patch to the array class to do this:

class Array
  def self.shared(a1, a2)
    utf = a1 - a2 #utf stands for 'unique to first', i.e. unique to a1 set (not in a2)
    a1 - utf
  end
end

The & operator is the correct answer here though. More elegant.