本文介绍了总和哈希值 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
值的大小求和.有没有简单的方法可以做到这一点?
and I would like to sum the size of each :hand
value in the array. Is there a simple way to do this?
所以输出将是每个 :hand.size
的总和.在上述情况下,输出将是 18
So the output would be the sum of each :hand.size
. In the above case the output would be 18
推荐答案
players.map { |player| player[:hand].size }.reduce(:+) # => 18
这篇关于总和哈希值 Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!