遍历Ruby哈希数组并计数.价值出现了多少次? [英] Iterating over array of Ruby Hashes and counting the no. of times value has appeared?

查看:181
本文介绍了遍历Ruby哈希数组并计数.价值出现了多少次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有结构的哈希表的Ruby数组

I have a Ruby array of Hashes with structure

[{:fruit=>"apple"}, {:fruit=>"apple"}, {:fruit=>"apple"}, {:fruit=>"banana"}, {:fruit=>"banana"}, {:fruit=>"pineapple"}].

我想要一个最终的哈希值:

I want a final hash which will be:

{:apple => 3,:banana=> 2,:pineapple=>1}

如何做到这一点?

推荐答案

创建具有默认值的哈希,并遍历数组中的每个哈希:

Create an Hash with a default value and iterate over each hash in the array:

fruits = [{:fruit=>"apple"}, {:fruit=>"apple"}, {:fruit=>"apple"}, {:fruit=>"banana"}, {:fruit=>"banana"}, {:fruit=>"pineapple"}]
h = Hash.new(0)
fruits.each { |item| h[item[:fruit]] += 1 }

这篇关于遍历Ruby哈希数组并计数.价值出现了多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆