给出像这样的哈希:
{ "key_1" => ["value1","value2","value3"], "key_2" => ["value4","value5"], ...}
我怎样才能获得这样的哈希:
{ "value1" => "key_1", "value2" => "key_1", "value3" => "key_1", "value4" => "key_2", "value5" => "key_2" }
我试过这个:
Hash[original_hash.flat_map { |key, values| original_hash.map { |value| [value, key] } }]
答案 0 :(得分:4)
hash.each_with_object({}) { |(key,values),h| values.each { |v| h[v] = key } }
答案 1 :(得分:1)
就像正常一样迭代哈希:
h = { "key_1" => ["value1","value2","value3"], "key_2" => ["value4","value5"]}
newh = {}
h.each do |key, vals|
vals.each { |v| newh[v] = key }
end
p newh
#=> {"value1"=>"key_1", "value2"=>"key_1", "value3"=>"key_1", "value4"=>"key_2", "value5"=>"key_2"}
答案 2 :(得分:0)
鉴于此哈希:
> h = { "key_1" => ["value1","value2","value3"], "key_2" => ["value4","value5"]}
=> {"key_1"=>["value1", "value2", "value3"], "key_2"=>["value4", "value5"]}
你可以这样做:
> h.map{ |k, v| v.map{ |f| { f => k }}}.flatten
=> [{"value1"=>"key_1"}, {"value2"=>"key_1"}, {"value3"=>"key_1"}, {"value4"=>"key_2"}, {"value5"=>"key_2"}]
更新回答:
> h.inject({}){ |h, (k,v)| v.each{ |f| h[f] = k }; h }
=> {"value1"=>"key_1", "value2"=>"key_1", "value3"=>"key_1", "value4"=>"key_2", "value5"=>"key_2"}
答案 3 :(得分:0)
鉴于你的哈希:
Hash = { "key_1" => ["value1","value2","value3"], "key_2" => ["value4","value5"]}
我打电话给你的哈希,"哈希",以便我们可以反转它。反转散列会切换键和值对。
Hash ={ "key_1" => ["value1","value2","value3"], "key_2" => ["value4","value5"]}
inverseHash = Hash.invert
所以,我打电话给倒置了," inverseHash"。如果你把这个inverseHash,你得到你的结果:
puts inverseHash
以上代码输出:
{["value1", "value2", "value3"]=>"key_1", ["value4", "value5"]=>"key_2"}