我有以下几点
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中有什么优雅的方式做到这一点吗?
发布于 2012-06-27 23:42:17
Hash[friends.map { |f| _f = f.dup; [_f.delete(:name), _f] }]
# => {"Jack"=>{:attr1=>"def", :attr2=>"def"}, "Jill"=>{:attr1=>"def", :attr2=>"def"}}发布于 2012-06-27 23:44:09
friends.each_with_object({}) do |f, o|
f = f.dup
o[f.delete :name] = f
end发布于 2012-06-27 23:45:53
hash = {}
friends.each{|h| hash[h.delete(:name)] = h }
# => {"Jack"=>{:attr1=>"def", :attr2=>"def"}, "Jill"=>{:attr1=>"def", :attr2=>"def"}}https://stackoverflow.com/questions/11230022
复制相似问题