Rails - Find intersections between multiple arrays

I am trying to find intersection values โ€‹โ€‹between multiple arrays.

eg

code1 = [1,2,3] code2 = [2,3,4] code3 = [0,2,6] 

So the result will be 2

I know in PHP, you can do this with array_intersect

I wanted to easily add an additional array, so I really don't want to use multiple loops

Any ideas?

Thanks, Alex

+54
arrays ruby ruby-on-rails array-intersect
Jul 07 '10 at 17:47
source share
2 answers

Use the & Array method which for the given intersection.

For example:

 > [1,2,3] & [2,3,4] & [0,2,6] => [2] 
+87
Jul 07 '10 at 17:51 on
source share

If you need an easier way to do this with an array of unknown length, you can use the inject command.

 > 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] 
+34
Feb 12 '13 at 19:50
source share



All Articles