简体   繁体   English

如何反转我的哈希(切换键/值)并按值分组

[英]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.

相关问题 如何将键/值对添加到我的散列中? - How do I add a key/value pair into my hash? Rails-如何将具有哈希值的字符串的任何键更改为数组 - Rails - How do I change any key that has a string for a value in a hash into arrays 如何在视图中显示哈希中的特定键值对? - How do I display specific key value pairs from a hash in the view? 如何删除哈希数组中的键和值? - How I can delete key and value in array of hash? 如果第一个键不存在,如何在哈希中使用键的另一个值,比如ruby / rails中的某种类型的回退? - How do I use another value of a key in a hash if the first one doesn't exist, like some type of fallback in ruby/rails? 如何使用ajax手动构造其值等于另一个哈希的params哈希键? - How can I manually construct a params hash key whose value equals to another hash with ajax? 如何根据内部哈希中的键值最有效地按顺序遍历哈希哈希? - How can I most efficiently iterate over a hash of hashes in order based on key value in inner hash? 密钥相同时如何附加哈希值 - How to append hash value when key is same 如何从此哈希中访问值? - How do I access a value from within this hash? 我如何在存储在哈希中的数组内搜索字符串值 - how do I search for a string value inside an array stored in a hash
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM