Remove duplicate elements from array in Ruby

2019-01-29 16:53发布

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?

6条回答
何必那么认真
2楼-- · 2019-01-29 17:10

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]
查看更多
家丑人穷心不美
3楼-- · 2019-01-29 17:16
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.

查看更多
来,给爷笑一个
4楼-- · 2019-01-29 17:19

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]
查看更多
疯言疯语
5楼-- · 2019-01-29 17:28

You can also return the intersection.

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

This will also delete duplicates.

查看更多
叛逆
6楼-- · 2019-01-29 17:31

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
查看更多
等我变得足够好
7楼-- · 2019-01-29 17:32

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 }
查看更多
登录 后发表回答