86

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

3 Answers 3

130

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

For example:

> [1,2,3] & [2,3,4] & [0,2,6]
=> [2]
Sign up to request clarification or add additional context in comments.

2 Comments

@Anurag Are you sure this works? Unless I'm misunderstanding OP's requirements, the first and last arrays aren't tested against one-another for intersection. E.g., [1,2,3] & [4,5,6] & [1,2,3] returns an empty array.
@Cyle any element in the result of a three-way intersection should exist in all three operands. See en.wikipedia.org/wiki/Intersection_(set_theory)
57

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]

1 Comment

arrays.inject(:&) will not work in 1.9. this will work though arrays.inject(:'&')
5

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]

3 Comments

Are both methods the same?
@Christopher Oezbek, almost. If you click on "click to toggle source" in the docs you will see that "intersection" is calling "&" under the hood.
This is a nice addition. Convenient to have it described in the method name as well as being able to chain it nicely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.