{

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to install and uninstall gem in Ruby Programming| Ruby on Rails by Example

How to do sum of array numbers in Ruby with examples

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to convert Class or Hash Object to JSON Object Ruby| Ruby on Rails By Example

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to print the name of a Ruby class| Ruby on Rails By Example