Ruby 3.1 adds Array#intersect? method


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:

a = [1, 2, 3]
b = [2, 3, 5, 7]
c = [5, 3, 8, 7]

a.intersection(b)
=> [2, 3]

a.intersection(b, c)
=> [3]

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.

a = [1, 2, 3]
b = [2, 3, 5, 7]

a.intersection(b).any?
=> true

a.intersection(b).empty?
=> 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.

a = [1, 2, 3]
b = [2, 3, 5, 7]
c = [4, 7, 9]

a.intersect?(b)
=> true

a.intersect?(c)
=> false

Note

Unlike #intersection method which accepts multiple arrays as argument we cannot pass multiple arrays to #intersect method.

a.intersect?(b, c)
=> ArgumentError (wrong number of arguments (given 2, expected 1))