I have a Ruby array which contains duplicate elements.
array = [1,2,2,1,4,4,5,6,7,8,5,6]
How can I remove all the duplicate elements from this array while retaining all unique elements without using for-loops and iteration?
I have a Ruby array which contains duplicate elements.
array = [1,2,2,1,4,4,5,6,7,8,5,6]
How can I remove all the duplicate elements from this array while retaining all unique elements without using for-loops and iteration?
If someone was looking for a way to remove all instances of repeated values, see this question.
The uniq method removes all duplicate elements and retains all unique elements in the array.
One of many beauties of Ruby language.
Just another alternative if anyone cares.
You can also use the
to_set
method of an array which converts the Array into a Set and by definition, set elements are unique.You can also return the intersection.
This will also delete duplicates.
Try with XOR Operator in Ruby:
You can remove the duplicate elements with the uniq method:
What might also be useful to know is that the uniq method takes a block, so e.g if you a have an array of keys like this:
and you want to know what are the unique files, you can find it out with: