本文翻译自:Remove duplicate elements from array in Ruby
I have a Ruby array which contains duplicate elements. 我有一个包含重复元素的Ruby数组。
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? 如何在不使用for循环和迭代的情况下保留所有唯一元素的同时从此数组中删除所有重复元素?
参考:https://stackoom.com/question/Z6Iz/从Ruby中删除数组中的重复元素
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]
You can also return the intersection. 你也可以返回十字路口。
a = [1,1,2,3]
a & a
This will also delete duplicates. 这也将删除重复项。
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. 您还可以使用数组的to_set
方法将Array转换为Set,根据定义,set元素是唯一的。
[1,2,3,4,5,5,5,6].to_set => [1,2,3,4,5,6]
Try with XOR Operator in Ruby: 尝试使用Ruby中的XOR运算符:
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
array = array.uniq
The uniq method removes all duplicate elements and retains all unique elements in the array. uniq方法删除所有重复元素并保留数组中的所有唯一元素。
One of many beauties of Ruby language. Ruby语言的众多美女之一。