如何将带有'array'键的红宝石哈希转换为Ruby中的嵌套哈希?

问题描述 投票:2回答:1

我试图弄清楚如何转换这样的复杂哈希:

{
  ["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"}
  }
}

任何人都非常欢迎!

arrays ruby hash key
1个回答
0
投票
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"}}}

© www.soinside.com 2019 - 2024. All rights reserved.