When dealing with Arrays in Ruby we frequently come across cases, where we want to find the intersection of arrays.
Our previous blog
post,
refers to Array#intersection
method,
which was used to return the common elements between arrays as shown below:
But in few cases, we only want to check if arrays intersect without knowing the result.
Before
Before Ruby 3.1, we would chain the intersection
method with #any?
or #empty?
to check if the result is true or false.
The above approach will first compute the intersection array and then evaluate
#any?
or #empty?
on the result.
After
To save memory and improve performance, Ruby 3.1
added
Array#intersect?
method which returns true
if two arrays
have at least one element in common, otherwise returns false
.
Note
Unlike #intersection
method which accepts multiple arrays as argument we cannot pass multiple arrays to
#intersect
method.