Remove Duplicates From a Ruby Array

Nurudeen Ibrahim Apr 28, 2022
  1. Remove Duplicates From a Ruby Array Using the uniq Method
  2. Remove Duplicates From a Ruby Array by Converting to a Set
  3. Remove Duplicates From a Ruby Array Using Set Operations
Remove Duplicates From a Ruby Array

The following are different methods of removing duplicates from an array in Ruby.

Remove Duplicates From a Ruby Array Using the uniq Method

The uniq method is the most common approach for removing Ruby array duplicates.

Example code:

arr = [1, 2, 3, 3, 7, 4, 4]
p arr.uniq

Output:

[1, 2, 3, 7, 4]

Remove Duplicates From a Ruby Array by Converting to a Set

Another way of removing duplicates is by converting the array to a set.

Example Code:

arr = [1, 2, 3, 3, 7, 4, 4]
p arr.to_set.to_a

Output:

[1, 2, 3, 7, 4]

In the example above, we needed to convert to array (.to_a) again because the set is an entirely different data structure.

Remove Duplicates From a Ruby Array Using Set Operations

When a set operation is used on arrays, the arrays are implicitly converted to sets.

Using the intersection operator,

Example code:

arr = [1, 2, 3, 3, 7, 4, 4]
p(arr & arr)

Output:

[1, 2, 3, 7, 4]

Using the union operator,

Example code:

arr = [1, 2, 3, 3, 7, 4, 4]
p(arr | arr)

Output:

[1, 2, 3, 7, 4]

Related Article - Ruby Array