martini-bonanza
martini-bonanza

Reputation: 1591

How to find the intersection of n arrays in Ruby?

[1, 2, 3] & [2, 3, 4] gives us [2, 3] but how do you get the intersection of n arrays?

[[1, 2, 3], [2, 3, 4], [1, 3, 4]].something would give [3]

Looping with & works but there must be a better way.

Upvotes: 2

Views: 200

Answers (2)

Data Don
Data Don

Reputation: 338

Just & all arrays. Suppose you have 3 arrays.

a = [1,2,3]
b = [2,3,4]
c = [3,4,5]

a & b & c
=> [3]

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118261

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

Upvotes: 8

Related Questions