HomeSearch

Ruby Remove Duplicates From Array

Use the uniq method to remove duplicate elements from arrays with minimal code.
Remove duplicates. In an array, any element value may occur. But often we want just unique, non-duplicate elements. We invoke the uniq method to correct this problem.Array
Uniq and "uniq!" remove all except the first element with a value. But often programs are more efficient (and easier to understand) when values are kept in a hash, which eliminates dupes.
Let us begin with a couple arrays. We first create an array containing integers. The array has two duplicated numbers: a 2 and a 3. We invoke the "uniq!" method, which operates in-place.

So: When we call "uniq!" we do not assign another array to it. The methods imply changes the "values" array, which we reuse.

Next: We create an array of strings. This one has three string values equalling "dog."

Uniq: We call uniq and assign another array to it result. Two of the "dog" values were eliminated. They must have run away.

Ruby program that uses uniq, arrays # An input array. values = Array[4, 1, 2, 2, 3, 3] print values, "\n" # Convert the array with uniq. values.uniq! print values, "\n" # A string array. names = Array["cat", "dog", "dog", "dog", "mouse"] print names, "\n" # Create array copy with only unique values. unique = names.uniq print unique, "\n" Output [4, 1, 2, 2, 3, 3] [4, 1, 2, 3] ["cat", "dog", "dog", "dog", "mouse"] ["cat", "dog", "mouse"]
Find duplicates. This method uses the each iterator over on an array, and uses a hash to record which elements have been encountered. It then reports duplicates as it locates them.

Note: This method is efficient because it uses a hash to search for duplicates. But avoiding duplicates in the first place would be faster.

Ruby program that finds duplicates in an array def find_duplicates(elements) encountered = {} # Examine all elements in the array. elements.each do |e| # If the element is in the hash, it is a duplicate. if encountered[e] puts "Dupe exists for: " << e else # Record that the element was encountered. encountered[e] = 1 end end end # Use the example method. elements = ["bird", "dog", "bird", "cat"] find_duplicates(elements) Output Dupe exists for: bird
In Ruby, we find many convenience methods. Uniq is one. In many languages, such functions must be developed or packaged into custom, reusable libraries. Ruby makes this unnecessary.
With a hash, we can eliminate duplicates automatically—this makes more sense for many programs. Ordering is lost in this way. Uniq meanwhile retains ordering.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls