Ruby 3.1 adds Array#intersect?

Ashik Salman

Ashik Salman

May 11, 2021

This blog is part of our  Ruby 3.1 series.

Ruby 3.1 introduces the Array#intersect? method which returns boolean value true or 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.

=> x = [1, 2, 5, 8]
=> y = [2, 4, 5, 9]
=> z = [3, 7]

=> x.intersection(y) # x & y
=> [2, 5]

=> x.intersection(z) # x & z
=> []

The intersection or & methods return an empty array or array having the common elements in it as result. We have to further call empty?, any? or blank? like methods to check whether two arrays intersect each other or not.

Before Ruby 3.1

=> x.intersection(y).empty?
=> false

=> (x & z).empty?
=> true

=> (y & z).any?
=> false

After Ruby 3.1

=> x.intersect?(y)
=> true

=> y.intersect?(z)
=> false

The Array#intersect? method accepts only single array as argument, but Array#intersection method can accept multiple arrays as arguments.

=> x.intersection(y, z) # x & y & z
=> []

The newly introduced intersect? method is faster than the above described checks using intersection or & 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.

Here's the relevant pull request and feature discussion for this change.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.