[英]how do I invert my hash (switch key/value) and group by value
I have a hash in rails like so: 我有这样的哈希值:
{"unique_id" => "1",
"unique_id2" => "2",
"unique_id3" => "n"}
Each unique key has a count that can be a number 1-20. 每个唯一键的计数可以是1-20。 What I would like to do is have a hash that looks like this: 我想做的是拥有一个看起来像这样的哈希:
{"1" => ["unique_id", "unique_id2"],
"2" => ["unique_id3"],
"3" => ["unique_id4", "unique_id5", "uniqueid6"]}
How would I go about doing that with a hash? 我将如何使用哈希进行操作?
Not too hard! 不是太难!
hash = { "unique_id" => "1",
"unique_id2" => "2",
"unique_id3" => "n"
}
new_hash = hash.each_with_object({}) { |(k,v), h| (h[v] ||= []) << k }
each_with_object({})
is just an each loop with a blank hash each_with_object({})
只是一个带有空白哈希的循环
||= []
means if the hash doesn't have a value for v
, set it equal to an empty array ||= []
表示如果哈希没有v
的值,则将其设置为一个空数组
<< k
pushes the key onto the array << k
将键推到数组上
Try this: 尝试这个:
h.group_by{|k,v| v }.each{|k,v| v.map!(&:first) }
group_by
takes your hash and groups it by value group_by
获取您的哈希并按值将其分组
each
iterates over the result hash each
迭代结果哈希
map!
maps the first elements of the result value arrays, since group_by
on a Hash
returns two-dimensional Array
s with the structure [key, value]
映射结果值数组的第一个元素,因为Hash
上的group_by
返回具有[key, value]
结构的二维Array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.