Remove duplicate elements from array in Ruby

◇◆丶佛笑我妖孽 提交于 2019-11-29 18:41:08
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.

You can also 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 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 }
Lri

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]

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]

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