gpt4 book ai didi

ruby : Generate a Hash of Hashes from an Array of Hashes

转载 作者:太空宇宙 更新时间:2023-11-03 17:01:37 26 4
gpt4 key购买 nike

我有以下内容

friends = [{ name: "Jack", attr1:"def", attr2:"def" }, { name: "Jill", attr1:"def", attr2:"def" }]

我想把上面的表示转换成这样的哈希的哈希

friends = { "Jack" => { attr1: "def", attr2:"def" }, "Jill" => { attr1: "def", attr2: "def" } }

在 Ruby 中有什么优雅的方法可以做到这一点?

最佳答案

Hash[friends.map { |f| _f = f.dup; [_f.delete(:name), _f] }]
# => {"Jack"=>{:attr1=>"def", :attr2=>"def"}, "Jill"=>{:attr1=>"def", :attr2=>"def"}}

关于 ruby : Generate a Hash of Hashes from an Array of Hashes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11230022/

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