简体   繁体   中英

How do I add the two values together in this Ruby Hash?

我想将此哈希值加在一起,然后输出总数。

b = {"Mike"=>100, "Jim"=>20}

You do as below

hash = {"Mike"=>100, "Jim"=>20}
hash.values.reduce(:+) # => 120
# or
hash.reduce(0) { |sum,(_, v)| sum + v } # => 120

Read this powerful method Enumerable#reduce .

b.values.inject(:+)

将工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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