There Are Four Lights
There Are Four Lights

Reputation: 1426

Dynamic intersection in Ruby Arrays

I have an set of Arrays. The number of Arrays is dynamic, it could be one, could be 100. In this example it's 3:

arr = [[1,2,3,4], [2,4], [2,3,4]]

What I need as result is to find same (intersecting) value(s) from all arrays. So result should be:

#=> [2,4]

How it could be done a proper way?

Upvotes: 1

Views: 154

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369448

You can use Array#& to find the (set) intersection of arrays:

arr.inject(:&)
# => [2, 4]

Upvotes: 6

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

arr.reduce &:&
#⇒ [
#  [0] 2,
#  [1] 4
# ]

Upvotes: 5

Related Questions