0
0
RubyHow-ToBeginner · 3 min read

How to Find Intersection of Arrays in Ruby Easily

In Ruby, you can find the intersection of arrays using the & operator, which returns a new array containing elements common to both arrays. For example, array1 & array2 gives the shared elements between array1 and array2.
📐

Syntax

The intersection of two arrays in Ruby is found using the & operator between them. This operator returns a new array with elements that appear in both arrays, without duplicates.

  • array1 & array2: Returns common elements.
ruby
common_elements = array1 & array2
💻

Example

This example shows how to find common elements between two arrays using the & operator.

ruby
array1 = [1, 2, 3, 4, 5]
array2 = [3, 4, 5, 6, 7]
common = array1 & array2
puts common.inspect
Output
[3, 4, 5]
⚠️

Common Pitfalls

One common mistake is trying to use methods like intersection without knowing they exist (available in Ruby 2.7+). Another is expecting duplicates to be preserved; the & operator removes duplicates in the result.

Also, using array1 & array2 only works for arrays, not other enumerable types.

ruby
wrong = [1, 2, 2, 3] & [2, 2, 4]
# Result is [2], duplicates removed

# Correct if duplicates matter, use select:
correct = [1, 2, 2, 3].select { |e| [2, 2, 4].include?(e) }
puts wrong.inspect
puts correct.inspect
Output
[2] [2, 2]
📊

Quick Reference

  • &: Finds unique common elements between arrays.
  • intersection: Alias for & in Ruby 2.7+.
  • select + include?: To preserve duplicates in intersection.

Key Takeaways

Use the & operator to find unique common elements between arrays in Ruby.
The & operator removes duplicates in the result; use select with include? to keep duplicates.
Ruby 2.7+ supports the intersection method as an alias for &.
The intersection works only on arrays, not other enumerable types.
Always inspect the result to understand how duplicates are handled.