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. 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
||= []
means if the hash doesn't have a value for v
, set it equal to an empty array
<< k
pushes the key onto the array
Try this:
h.group_by{|k,v| v }.each{|k,v| v.map!(&:first) }
group_by
takes your hash and groups it by value
each
iterates over the result hash
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.