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?
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
array = array.uniq
uniq
removes all duplicate elements and retains all unique elements in the array.
This is one of many beauties of the Ruby language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With