Cameron Bass Cameron Bass - 3 months ago 8
Ruby Question

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.

Answer

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.