84

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

Anurag
  • 140,337
  • 36
  • 221
  • 257
Alex
  • 6,205
  • 7
  • 43
  • 53

3 Answers3

129

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

For example:

> [1,2,3] & [2,3,4] & [0,2,6]
=> [2]
highBandWidth
  • 16,751
  • 20
  • 84
  • 131
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • @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. – Noz Apr 23 '13 at 18:56
  • 2
    @Cyle any element in the result of a three-way intersection should exist in all three operands. See http://en.wikipedia.org/wiki/Intersection_(set_theory) –  Apr 24 '13 at 02:36
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]
Fotios
  • 3,643
  • 1
  • 28
  • 30
4

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]
Marian13
  • 7,740
  • 2
  • 47
  • 51