我试图弄清楚如何转换这样的复杂哈希:
{
["A", "B"]=>{"id"=>123,"name"=>"test"},
["A", "F"]=>{"id"=>236,"name"=>"another test"},
["C", "F"]=>{"id"=>238,"name"=>"anoother test"}
}
进入更复杂的哈希,例如
{
"A"=>{
"B"=>{"id"=>123,"name"=>"test"},
"F"=>{"id"=>236,"name"=>"another test"}
},
"C"=>{
"F"=>{"id"=>238,"name"=>"anoother test"}
}
}
任何人都非常欢迎!
each_with_object
可能是拯救者:hash.each_with_object(Hash.new {|h, k| h[k] = {}}) do |(k, v), memo|
memo[k.first].merge!(k.last => v)
end
#=> {"A"=>{"B"=>{"id"=>123, "name"=>"test"},
# "F"=>{"id"=>236, "name"=>"another test"}},
# "C"=>{"F"=>{"id"=>238, "name"=>"anoother test"}}}