Ruby 3.1 adds Array#intersect?

Ashik Salman

By Ashik Salman

on 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.

1=> x = [1, 2, 5, 8]
2=> y = [2, 4, 5, 9]
3=> z = [3, 7]
5=> x.intersection(y) # x & y
6=> [2, 5]
8=> x.intersection(z) # x & z
9=> []

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

1=> x.intersection(y).empty?
2=> false
4=> (x & z).empty?
5=> true
7=> (y & z).any?
8=> false

After Ruby 3.1

1=> x.intersect?(y)
2=> true
4=> y.intersect?(z)
5=> false

The 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 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 you liked this blog, you might also like the other blogs we have written. Check out the full archive.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, React.js, React Native, remote work,open source, engineering & design.