Sum Hash值Ruby

我有一系列哈希

players = [{:id=>1, :name=>"Alda", :dice_count=>5, :hand=>[6, 5, 2, 4, 3]}, {:id=>2, :name=>"Gonzalo", :dice_count=>5, :hand=>[1, 5, 1, 1]}, {:id=>3, :name=>"Markus", :dice_count=>5, :hand=>[6, 2, 5, 1]}, {:id=>4, :name=>"Luella", :dice_count=>5, :hand=>[4, 5, 1, 6, 5]}] 

我想总结每个的大小:hand数组中的:hand值。 有一个简单的方法吗?

所以输出将是每个的总和:hand.size 。 在上面的例子中,输出将是18

 players.map { |player| player[:hand].size }.reduce(:+) # => 18 

单程解决方案:

 players.inject(0) { | a, e | a + e[:hand].size } # => 18 

注意inject只是reduce另一个名称。

这个只是为了好玩,假设hand总是哈希中的最后一个元素。

 p players.map(&:flatten).map(&:last).map(&:size).reduce(:+)