"id", "value"=>"123"}, {"name"=>"type", "value"=>"app"}, {"-6ren">
gpt4 book ai didi

ruby - 如何从数组中获取哈希值

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:32 24 4
gpt4 key购买 nike

输入:-

array = [{"name"=>"id", "value"=>"123"}, 
{"name"=>"type", "value"=>"app"},
{"name"=>"codes", "value"=>"12"},
{"name"=>"codes", "value"=>"345"},
{"name"=>"type", "value"=>"app1"}]

sample_hash = {}

功能:-

array.map {|f| sample_hash[f["name"]] = sample_hash[f["value"]] }

结果:-

样本哈希

 => {"id"=>"123", "type"=>"app", "codes"=>"345"} 

但我需要的预期结果应该如下所示:-

样本哈希

 => {"id"=>"123", "type"=>["app","app1"], "codes"=>["12", "345"]} 

如何获得预期的输出?

最佳答案

您可以使用 new {|hash, key| 初始化 sample_hash block } 哈希构造函数,使此哈希中的值默认初始化为空数组。这使得第二阶段更容易,初始数据集中的每个值都附加到相应“名称”下索引的值数组中:

sample_hash = Hash.new { |h, k| h[k] = [] }
array.each { |f| sample_hash[f['name']] << f['value'] }

Try it online

关于ruby - 如何从数组中获取哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29486423/

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