7

Ruby 3.1 adds Array#intersect? method

 3 years ago
source link: https://blog.saeloun.com/2021/05/18/ruby-adds-array-intersect
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Ruby 3.1 adds Array#intersect? method

May 18, 2021 , by Alkesh Ghorpade 1 minute read

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))

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK