如何计算数组中散列中的所有元素的数量?

时间:2019-03-14 21:33:23

标签: ruby

基本上,我有一个包含3个散列的数组。我想计算并返回散列中的每个键和值,其中包括所有重复项。代码在下面,我已经完成了代码的初稿,您可以在下面亲自看到。

my_array = [{:name => "blake"}, {:name => "blake"}, {:name => "ashley"}]
 #Count the number of times each element appears inside the hash
 #so the output should have the number of times the :names, "blake" and "ashley" element appears
 #EXPECTED OUTPUT: :name = 3, "blake" = 2, "ashley" = 1

def getOccurances(array)
  array.group_by{|v| v[:name]}.map{|k,v| {name: k, count: v.length}}
end 

getOccurances(my_array)
#ACTUAL OUTPUT: {:name => "blake", :count => 2}, {:name => "ashley", :count => 1}

2 个答案:

答案 0 :(得分:1)

您可以将每个散列映射到[key,val]对的数组,然后展平每个出现的地方:

[{:name => "blake"}, {:name => "blake"}, {:name => "ashley"}].
    map(&:to_a).flatten.
    reduce(Hash.new { 0 }) {|o, v| o[v] += 1; o }

reduce的参数是使用块初始化的哈希,因此未初始化键的默认值为0;否则,默认值为0。我们只需遍历扁平化的条目并累积值的数量即可。

答案 1 :(得分:0)

my_array.each_with_object(Hash.new(0)) { |g,h| h[g[:name]] += 1 }.
         map { |k,v| { name: k, count: v } }
  #=> [{:name=>"blake", :count=>2}, {:name=>"ashley", :count=>1}]

注意:

my_array.each_with_object(Hash.new(0)) { |g,h| h[g[:name]] += 1 }
  #=> {"blake"=>2, "ashley"=>1}