user3843070
user3843070

Reputation: 81

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

I would like to add the values of this hash together, and output the total.

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

Upvotes: 1

Views: 106

Answers (2)

Johnson
Johnson

Reputation: 1749

b.values.inject(:+)

will work.

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118299

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.

Upvotes: 1

Related Questions