x = [:a, :b, :b, :b, :c, :c, :c]
counted = Hash[
x.group_by do |e|
x.count(e)
end.map do |count, items|
[count, items.uniq]
end
]
p counted[3] #=> [:b, :c]
這是如何工作的?讓我們按照步驟。首先,讓我們組的項目由數:
grouped_by_count = x.group_by do |e|
x.count(e)
end
這將產生與被計數密鑰的哈希值,並且是具有該計數非唯一的項目列表中的值:
p grouped_by_count
#=> {1=>[:a], 3=>[:b, :b, :b, :c, :c, :c]}
我們倒是真的寧願獨特項目,不過,讓我們做的變換:
grouped_by_count_unique = grouped_by_count.map do |count, items|
[count, items.uniq]
end
p grouped_by_count_unique
#=> [[1, [:a]], [3, [:b, :c]]]
這給了我們一個數組的數組,而不是一個哈希值。幸運的是,很容易把數組的數組到哈希:
counted = Hash[grouped_by_count_unique]
p counted
# => {1=>[:a], 3=>[:b, :c]}
現在只是把拼湊消除臨時對象,你會得到頂部的答案。
輝煌,謝謝,它也很優雅!我會冥想它。 – csikiati