Remove duplicate elements from array in Ruby

对着背影说爱祢 提交于 2019-12-18 09:54:34

问题


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?


回答1:


array = array.uniq

The uniq method removes all duplicate elements and retains all unique elements in the array.

One of many beauties of Ruby language.




回答2:


You can also return the intersection.

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

This will also delete duplicates.




回答3:


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 the uniq method takes a block, so e.g if you a have an array of keys like this:

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

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

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



回答4:


If someone was looking for a way to remove all instances of repeated values, see this question.

a = [1, 2, 2, 3]
counts = Hash.new(0)
a.each { |v| counts[v] += 1 }
p counts.select { |v, count| count == 1 }.keys # [1, 3]



回答5:


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.

[1,2,3,4,5,5,5,6].to_set => [1,2,3,4,5,6]



回答6:


Try with XOR Operator in Ruby:

a = [3,2,3,2,3,5,6,7].sort!

result = a.reject.with_index do |ele,index|
  res = (a[index+1] ^ ele)
  res == 0
end

print result


来源:https://stackoverflow.com/questions/8365721/remove-duplicate-elements-from-array-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!