We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
Ruby 3.1 introduces the
Array#intersect? method which returns boolean value
false based on the given input arrays have common elements in it.
We already know Array#intersection or Array#& methods which are used to find the common elements between arrays.
1=> x = [1, 2, 5, 8] 2=> y = [2, 4, 5, 9] 3=> z = [3, 7] 4 5=> x.intersection(y) # x & y 6=> [2, 5] 7 8=> x.intersection(z) # x & z 9=> 
& methods return an empty array or array having the
common elements in it as result. We have to further call
blank? like methods to check whether two arrays intersect each other or not.
1=> x.intersection(y).empty? 2=> false 3 4=> (x & z).empty? 5=> true 6 7=> (y & z).any? 8=> false
1=> x.intersect?(y) 2=> true 3 4=> y.intersect?(z) 5=> false
Array#intersect? method accepts only single array as argument, but
Array#intersection method can accept multiple arrays as arguments.
1=> x.intersection(y, z) # x & y & z 2=> 
The newly introduced
intersect? method is faster than the above described
& since the new method avoids creating an
intermediate array while evaluating for common elements. Also new method returns
true as soon as it finds a common element between arrays.