Rubyから配列内の重複要素を削除

1765 ワード

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ループと反復を使用せずにすべての一意の要素を保持し、この配列からすべての重複要素を削除するにはどうすればいいですか?
1階
参照先:https://stackoom.com/question/Z6Iz/Rubyから配列内の重複要素を削除
2階
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階
You can also return the intersection. 交差点に戻ってもいいです.
a = [1,1,2,3]
a & a

This will also delete duplicates. 重複も削除されます.
#4階
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]

#5階
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

#6階
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. ルビー言語の多くの美人の一人.