rails - Finding intersections between multiple arrays

Ruby on-RailsRubyArraysArray Intersect

Ruby on-Rails Problem Overview


I am trying to find the intersection values between multiple arrays.

for example

code1 = [1,2,3]
code2 = [2,3,4]
code3 = [0,2,6]

So the result would be 2

I know in PHP you can do this with array_intersect

I wanted to be able to easily add additional array so I don't really want to use multiple loops

Any ideas ?

Thanks, Alex

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Use the & method of Array which is for set intersection.

For example:

> [1,2,3] & [2,3,4] & [0,2,6]
=> [2]

Solution 2 - Ruby on-Rails

If you want a simpler way to do this with an array of arrays of unknown length, you can use inject.

> arrays = [code1,code2,code3]
> arrays.inject(:&)                   # Ruby 1.9 shorthand
=> [2]
> arrays.inject{|codes,x| codes & x } # Full syntax works with 1.8 and 1.9
=> [2]

Solution 3 - Ruby on-Rails

Array#intersection (Ruby 2.7+)

Ruby 2.7 introduced Array#intersection method to match the more succinct Array#&.

So, now, [1, 2, 3] & [2, 3, 4] & [0, 2, 6] can be rewritten in a more verbose way, e.g.

[1, 2, 3].intersection([2, 3, 4]).intersection([0, 2, 6])
# => [2]

[1, 2, 3].intersection([2, 3, 4], [0, 2, 6])
# => [2]

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
QuestionAlexView Question on Stackoverflow
Solution 1 - Ruby on-RailsAnuragView Answer on Stackoverflow
Solution 2 - Ruby on-RailsFotiosView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMarian13View Answer on Stackoverflow