0
我有一个Mysql2::Result
,它有一堆行。结果在哈希格式为这样:尝试遍历散列,提取唯一键并添加值
{"thing_name" => "email", "count(*)" => 1000}
{"thing_name" => "email", "count(*)" => 800}
{"thing_name" => "ads", "count(*)" => 500}
{"thing_name" => "display", "count(*)" => 700}
我的目标是通过所有的这些迭代并创建具有每个关键之一,其计数与该键关联的值之和的新的哈希。
我可以成功迭代并将“thing_name”放在数组中,并在其上运行.uniq
以将重复项合并为一个条目,但我无法弄清楚如何关联这些值并对它们进行适当的数学运算。或者如何做这个哈希。
这里是我到目前为止的代码:
thing_type = results.collect {|row| row["thing_name"]}
thing_type = thing_type.uniq
任何帮助将非常感激。
非常感谢@robbrit!你能解释一下迭代器的hash [key]部分吗?那里我有点困惑。 –
在那里,希望这会有所帮助! – robbrit
打败了我。我会用Hash.new(0)代替。目前每次找不到密钥都会调用该块。使用Hash.new(0)它将返回0. –