我如何保持数组内部哈希内部所有元素的计数



基本上,我有一个包含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}

您可以将每个哈希映射到[key,val]对的数组,然后变平,每个出现:

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

reduce的参数是用一个块初始化的哈希,因此非初始化键的默认值为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} 

最新更新