How to use the ampersand (&) operator on two arrays in Ruby

The & operator, also known as the ampersand operator, is used on two arrays to determine the unique elements between the two. You can use the & operator when you want to get the set intersection. The & operator returns an array that contains elements that are unique and present in both arrays.

Syntax

array & other_array

Parameters

The & operator does not accept any parameters.

Return value

The return value is a new array that contains elements that are present and unique in both arrays.

Example

In the example below, we create several arrays and use the & operator to return new arrays with unique and similar elements.

# create arrays
arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 1, 6, 7, 5]
arr3 = ["a", "b", "c", "d", "e"]
arr4 = ["z", "c", "d", "x"]
arr5 = ["Ruby", "Java", "JavaScript", "Python"]
arr6 = ["C", "Java", "Python"]
arr7 = ["1ab", "2cd", "3ef", "4gh", "5ij"]
arr8 = ["5ij", "6kl", "3ef", "3ef"]
arr9 = [nil, "nil", "true", "false", true]
arr10 = [false, false]
puts "#{arr1 & arr2}" # [1, 2, 5]
puts "#{arr3 & arr4}" # ["c", "d"]
puts "#{arr5 & arr6}" # ["Java", "Python"]
puts "#{arr7 & arr8}" # ["3ef", "5ij"]
puts "#{arr9 & arr10}" # []

Free Resources