Search code examples
rubystringarraysintersect

How can I check if a Ruby array includes one of several values?


I have two Ruby arrays, and I need to see if they have any values in common. I could just loop through each of the values in one array and do include?() on the other, but I'm sure there's a better way. What is it? (The arrays both hold strings.)

Thanks.


Solution

  • Set intersect them:

    a1 & a2
    

    Here's an example:

    > a1 = [ 'foo', 'bar' ]
    > a2 = [ 'bar', 'baz' ]
    > a1 & a2
    => ["bar"]
    > !(a1 & a2).empty? # Returns true if there are any elements in common
    => true