Finding what is common to two arrays

Ruby

Ruby Problem Overview


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 do I type to show that ["pig", "dog", "cat"] are common between these two arrays?

Ruby Solutions


Solution 1 - Ruby

You can intersect the arrays using &:

array1 & array2

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

Solution 2 - Ruby

Set Intersection. Returns a new array containing elements common to the two arrays, with no duplicates, like:

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

You can also read a blog post about Array coherences

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmilesView Question on Stackoverflow
Solution 1 - RubyRaoul DukeView Answer on Stackoverflow
Solution 2 - RubyChristian RolleView Answer on Stackoverflow