"18", "friend_id"=>"17", "dis-6ren">
gpt4 book ai didi

ruby 为哈希数组设置哈希键

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

给定以下哈希数组,我如何创建一个以 friend_id 为键并以 dist 为值的新哈希?

results = [
{"user_id"=>"18", "friend_id"=>"17", "dist"=>"1"},
{"user_id"=>"18", "friend_id"=>"42", "dist"=>"1"},
{"user_id"=>"18", "friend_id"=>"43", "dist"=>"1"},
{"user_id"=>"18", "friend_id"=>"46", "dist"=>"2"}
]

desired_hash = {"17" => "1", "42" => "1", "43" => "1", "46" => "2"}

我试过 map 但值在一个数组中。我也尝试 flatten 结果,但它压平了键而不是值

最佳答案

results.each_with_object({}) { |g,h| h[g["friend_id"]] = g["dist"] }

results.each_with_object({}) { |g,h| h.update(g["friend_id"]=> g["dist"]) }

关于ruby 为哈希数组设置哈希键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009722/

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