C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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"]
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