Search for what is common to two arrays

Is there a way to compare two arrays and show what is common to both of them?

array1 = ["pig", "dog", "cat"] array2 = ["dog", "cat", "pig", "horse"] 

What should I print to show that ["pig", "dog", "cat"] are common between these two arrays?

+41
ruby
Aug 20 '10 at 17:09
source share
2 answers

You can traverse arrays with & :

 array1 & array2 

This will return ["pig", "dog", "cat"] .

+99
Aug 20 '10 at 17:13
source share

Set intersection. Returns a new array containing elements common to two arrays, without duplicates, for example:

 ["pig", "dog", "bird"] & ["dog", "cat", "pig", "horse", "horse"] # => ["pig", "dog"] 

You can also read the blog post on Array Matching

+1
Oct. 25 '16 at 18:54
source share



All Articles