首页 > 解决方案 > 如何将带有“数组”键的 ruby​​ 哈希转换为 Ruby 中的嵌套哈希?

问题描述

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

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

任何帮助都会非常受欢迎!

标签: arraysrubyhashkey

解决方案


each_with_object可能是救援:

hash.each_with_object(Hash.new {|h, k| h[k] = {}}) do |((first, last), v), memo|  
  memo[first].merge!(last => v)
end
#=> {"A"=>{"B"=>{"id"=>123, "name"=>"test"}, 
#          "F"=>{"id"=>236, "name"=>"another test"}}, 
#    "C"=>{"F"=>{"id"=>238, "name"=>"anoother test"}}}

推荐阅读