From: Robert Klemme Date: 2011-03-23T00:08:45+09:00 Subject: Re: summing values in a hash? On Tue, Mar 22, 2011 at 3:13 PM, Robert Dober wrote: > On Tue, Mar 22, 2011 at 2:05 PM, Robert Klemme > wrote: >> On Tue, Mar 22, 2011 at 2:01 PM, Adam Prescott wrote: >>> On Tue, Mar 22, 2011 at 12:57 PM, Jen wrote: >>> >>>> Is there an inbuilt method to sum all values in a hash and return the >>>> result? >>>> >>>> I.E something like puts hash[values].sum >>>> >>> >>> You could try >>> >>> hash.values.inject { |a, b| a + b } >>> >>> Alternatively, you have the shorter form, inject(&:+) or inject(:+) >>> depending on your version of Ruby. 1.8.7 and higher should support all >>> three. >> >> You should rather use a different idiom because your solution breaks >> for empty Hash: >> >> irb(main):001:0> {}.values.inject {|a,b|a+b} >> => nil >> irb(main):002:0> {}.values.inject(0) {|a,b|a+b} >> => 0 > slightly better, because working ;) >    .inject(0){|a,(_,b)|a+b} What do you mean by that? Where was my solution not working? robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/