Back to Blog

Ruby 3.1 adds Array#intersect?

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]
4
5=> x.intersection(y) # x & y
6=> [2, 5]
7
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
3
4=> (x & z).empty?
5=> true
6
7=> (y & z).any?
8=> false

After Ruby 3.1

1=> x.intersect?(y)
2=> true
3
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.


You might also like

If you liked this blog post, check out similar ones from BigBinary