{"id"=>123,"name"=>"test"}, ["A", "F"]=>{"id"=>236,"name"=>"-6ren">
gpt4 book ai didi

arrays - 如何将带有 'array' 键的 ruby​​ 哈希转换为 Ruby 中的嵌套哈希?

转载 作者:行者123 更新时间:2023-12-01 10:18:39 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何转换像这样的复杂散列:

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

关于arrays - 如何将带有 'array' 键的 ruby​​ 哈希转换为 Ruby 中的嵌套哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com