rails - Finding intersections between multiple arrays

Alex picture Alex · Jul 7, 2010 · Viewed 34.4k times · Source

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

Answer

Anurag picture Anurag · Jul 7, 2010

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

For example:

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