rails - Finding intersections between multiple arrays

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


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

For example:

> [1,2,3] & [2,3,4] & [0,2,6]
=> [2]

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]

Need Your Help

Change font for UIBarButtonItem

objective-c rubymotion

I am building an iOS app using Rubymotion and I need to set the font family to a custom font for a button in the navigation bar (UIBarButtonItem). I know I do it like this in Objective-C but how is...

Hooking document.createElement using function prototype


I want to hook onto the document.createElement function in such a way that, every time I create a div element, my hook will attach a "foo" attribute to the div. This is what I have currently: