Reputation: 8461
I have these two arrays
arr1 = ["dog", "cat", "bird"]
arr2 = ["fish", "bear", "bird"]
Notice how the only matching element is "bird" from the two arrays. I want to find a check that will say if any elements are matching return true.
For example this does not work arr1.include?(arr2)
but looking for method that will.
Upvotes: 2
Views: 1239
Reputation: 4615
I have found a good way to do this:
(arr1 & arr2).any?
&
is a logic operator, if some elements exist in both arrays, this will return these elements.
any?
checks if any elements exist in the array. If there exists at least one, then it return true
.
Upvotes: 4
Reputation: 471
You do this with intersection between two arrays and after this we can check if there are any matching elements in result.
(arr1 & arr2).present?
In your case we have
arr1 = ["dog", "cat", "bird"]
arr2 = ["fish", "bear", "bird"]
Result can be like this:
(arr1 & arr2).present?
It will return ['bird']
, so its not empty and the present? will return true.
Upvotes: 1
Reputation: 1316
arr1.any? { |item| arr2.include?(item) }
This will check if any item from first array is included in the second array.
Upvotes: 1