---
title: "Ruby 3.1 adds Array#intersect?"
description: "Ruby 3.1 adds Array#intersect?"
canonical_url: "https://www.bigbinary.com/blog/ruby-3-1-adds-array-intersect"
markdown_url: "https://www.bigbinary.com/blog/ruby-3-1-adds-array-intersect.md"
---

# Ruby 3.1 adds Array#intersect?

Ruby 3.1 adds Array#intersect?

- Author: Ashik Salman
- Published: May 11, 2021
- Categories: Ruby 3.1, Ruby

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#&](https://ruby-doc.org/core-3.0.1/Array.html#method-i-intersection)
methods which are used to find the common elements between arrays.

```ruby
=> 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

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

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

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

## After Ruby 3.1

```ruby
=> 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.

```ruby
=> 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](https://github.com/ruby/ruby/pull/1972) and
[feature discussion](https://bugs.ruby-lang.org/issues/15198) for this change.

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-3-1-adds-array-intersect)
