Remove duplicate elements from array in Ruby Remove duplicate elements from array in Ruby ruby ruby

Remove duplicate elements from array in Ruby


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.


You can return the intersection.

a = [1,1,2,3]a & a

This will also delete duplicates.


You can remove the duplicate elements with the uniq method:

array.uniq  # => [1, 2, 4, 5, 6, 7, 8]

What might also be useful to know is that uniq takes a block, so if you have a have an array of keys:

["bucket1:file1", "bucket2:file1", "bucket3:file2", "bucket4:file2"]

and you want to know what the unique files are, you can find it out with:

a.uniq { |f| f[/\d+$/] }.map { |p| p.split(':').last }