Ruby 3.1 Added intersect? Method To Array

May 15, 2021

While working on a Ruby project at times we may need to find whether two arrays have any common items.

In Ruby '&' operator is popularly used for this.

Let's quickly look at an example.

chocolate_cake_ingredients = ['egg', 'baking powder', 'sugar', 'chocolates'] vanilla_cake_ingredients = ['vanilla', 'baking powder', 'sugar'] chocolate_cake_ingredients & vanilla_cake_ingredients #=> ["baking powder", "sugar"]

Ruby 2.7.0 introduced Array#intersections which helped us to write more readable code.

We can write the above example as:

chocolate_cake_ingredients .intersection(vanilla_cake_ingredients) #=> ["baking powder", "sugar"]

Sometimes we simply require the result as boolean to use in conditional logic.

Mostly we use empty? or any? method to get the result as boolean.

(chocolate_cake_ingredients & vanilla_cake_ingredients).empty? #=> false !(chocolate_cake_ingredients & vanilla_cake_ingredients).empty? #=> true chocolate_cake_ingredients .intersection(vanilla_cake_ingredients).any? #=> true !chocolate_cake_ingredients .intersection(vanilla_cake_ingredients).any? #=> false

In above example, we get true or false value but at the cost of an intermediate array.

That means (chocolate_cake_ingredients & vanilla_cake_ingredients) is evaluated first
and result is stored in an intermediate array.
Then empty? method evaluates whether intermediate array has any element.

It would be better if there would have been a way to avoid creating an extra array.

In the other hand, Set#intersect? method helps us to directly evaluate whether two sets are intersecting each other.

However, we did not have an Array#intersect? method before Ruby 3.1 .

Finally, Ruby 3.1 added Array#intersect? with this pull request and we can refactor the above example:

chocolate_cake_ingredients .intersect?(vanilla_cake_ingredients) #=> true

Happy coding!

Share feedback with us at:

info@scriptday.com

© All rights reserved 2022