简体   繁体   English

获取 ruby 中所有键的总和

[英]Get the sum of all keys in ruby

How would I get the sum of keys if they have different values in ruby?如果它们在 ruby 中有不同的值,我将如何获得键的总和?

{"dog"=>1, "cat"=>3, "fish"=>5} = 9

The keys in your example are strings, the values are integers.您示例中的键是字符串,值是整数。 If you want the sum of the integers you can do hash.values.sum :如果你想要整数的总和,你可以做hash.values.sum

{"dog"=>1, "cat"=>3, "fish"=>5}.values.sum
#=> 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM