0

给定这样的哈希:

{ "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] } }]
4

4 回答 4

4
hash.each_with_object({}) { |(key,values),h| values.each { |v| h[v] = key } }
于 2012-10-28T09:58:56.807 回答
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"}
于 2012-10-28T09:50:20.307 回答
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"}
于 2012-10-28T09:51:51.193 回答
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"}
于 2016-10-04T16:19:06.867 回答