Bitwise
Bitwise

Reputation: 8461

Checking for individual matching elements in two different array

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

Answers (3)

Bartłomiej Gładys
Bartłomiej Gładys

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

BIlal Khan
BIlal Khan

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

jan.zikan
jan.zikan

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

Related Questions