How to remove duplicate elements from an array in Ruby with examples

Arrays contain duplicate elements. Sometimes we want to remove duplicate elements.

There are multiple ways to return unique elements in Ruby Array.

  • uniq method
  • to_set method

How to return unique elements from an array in Ruby

The first method is using the Array uniq method. Array provides a uniq method that returns an array of elements by removing duplicate elements.

array = [8,1,7,1,5,3,4,8]
array = array.uniq
puts array

The second way is using the Array.to_set method.

The to_set() method converts Array to Set and, Set stores the unique elements. to_a method used to convert Set to Array.

array = [8,1,7,1,5,3,4,8]
array = array.to_set.to_a
puts array

With this, It again takes intermediate storage for storing the set data.

The third way, using the intersection operator (&) in Ruby which returns the array containing elements that are common in multiple arrays.

array = [8,1,7,1,5,3,4,8]
array = array & array
puts array

Output:

8
1
7
5
3
4

Conclusion

Learned multiple ways to remove duplicate elements from an array.

array uniq method is the best way in terms of performance and readability.