ruby - 如何计算哈希数组中的值

标签 ruby arrays hash

我有一个哈希数组

[ {:name => "bob", :type => "some", :product => "apples"},
  {:name => "ted", :type => "other", :product => "apples"},.... 
  {:name => "Will", :type => "none", :product => "oranges"} ]

并且想知道是否有一种简单的方法来计算产品的数量并将计数以及值存储在数组或哈希中。

我希望结果是这样的:

@products =  [{"apples" => 2, "oranges => 1", ...}]

最佳答案

你可以这样做

array = [
  {:name => "bob", :type => "some", :product => "apples"},
  {:name => "ted", :type => "other", :product => "apples"},
  {:name => "Will", :type => "none", :product => "oranges"} 
]

array.each_with_object(Hash.new(0)) { |h1, h2| h2[h1[:product]] += 1 }
# => {"apples"=>2, "oranges"=>1}

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

相关文章:

ruby-on-rails - Ruby,从文本中获取第一张图片

ruby-on-rails - 将 Timecop gem 用于范围

php - 将数组定义为函数调用的一部分是不好的做法吗?

c++ - 如何创建迭代器的 QSet

python - 在 Python 中创建一个包含 70 万个项目的字典?

ruby-on-rails - Ruby on Rails - redirect_to 'index' 和 redirect_to objects_path & redirect_to action : 'index' 之间的区别

Ruby,mixin 实例变量和方法

arrays - 在 Swift 3 中扩展类型化数组(基本类型如 Bool)?

javascript - 找到数组中最长的不重复元素,然后返回其原始值

mysql - 在 MySQL 对表进行分区时,这里如何使用 DIV 作为 HASH 分区定义的一部分?