Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 845
Colen Avatar asked Apr 08 '10 22:04

Colen


People also ask

How do you check if an array contains multiple values?

To check if multiple values exist in an array:Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .

How can you test if an item is included in an array Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

How do you find the subset of an array in Ruby?

slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.

How do you compare two arrays in Ruby?

Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.


2 Answers

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 
like image 152
Mark Byers Avatar answered Nov 11 '22 04:11

Mark Byers


Any value in common ? you can use the intersection operator : &

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ] 

If you are looking for a full intersection however (with duplicates) the problem is more complex there is already a stack overflow here : How to return a Ruby array intersection with duplicate elements? (problem with bigrams in Dice Coefficient)

Or a quick snippet which defines "real_intersection" and validates the following test

class ArrayIntersectionTests < Test::Unit::TestCase       def test_real_array_intersection     assert_equal [2], [2, 2, 2, 3, 7, 13, 49] & [2, 2, 2, 5, 11, 107]     assert_equal [2, 2, 2], [2, 2, 2, 3, 7, 13, 49].real_intersection([2, 2, 2, 5, 11, 107])     assert_equal ['a', 'c'], ['a', 'b', 'a', 'c'] & ['a', 'c', 'a', 'd']     assert_equal ['a', 'a', 'c'], ['a', 'b', 'a', 'c'].real_intersection(['a', 'c', 'a', 'd'])   end end 
like image 28
Jean Avatar answered Nov 11 '22 05:11

Jean