arrays - 如何将带有“数组”键的 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"}
}
}
任何帮助都会非常受欢迎!
解决方案
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"}}}
推荐阅读
- javascript - 如何在 Typescript 中使 Promise 类型安全?
- c++ - 菜单选择错误,找不到任何解决方案。未找到菜单标识符
- c# - 如何隐藏 ac# .exe 的配置文件?
- javascript - 自动填充元素 WKWebView
- java - Java中的正弦到弧度或度数
- angular - 当我尝试将数据添加到表中时,它显示类型错误
- python - Django:在html页面中检索表数据
- python - 如何将数据从文件加载到代码并使用它
- windows - 没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme Core 3.1
- r - 滞后线性回归