From: Alex Fort Date: 2010-06-15T23:41:12+09:00 Subject: Re: Unexpected behavior in inject On Tue, Jun 15, 2010 at 10:31 AM, Jonathan Nielsen wrote: >> [1,2,3].inject(0) do |acc, num| >>  acc + num >>  puts acc >> end >> >> >> Ruby gives me this error: >> >> bash ~ $ ruby test.rb >> 0 >> test.rb:2: undefined method `+' for nil:NilClass (NoMethodError) >>        from test.rb:5:in `inject' >>        from test.rb:1:in `each' >>        from test.rb:1:in `inject' >>        from test.rb:1 >> >> This seems pretty strange to me, as if puts is modifying the accumulator by >> resetting it to nil. Is this normal behavior? If so, I would greatly >> appreciate it if someone could point me in the right direction as to why >> this is the way it is. > > > Yes, this is exactly as expected.  The last statement you put in the block > is the return value of the block.  'puts' always returns nil, so the next > iteration acc is nil. > > To get the behavior you are looking for: > > [1,2,3].inject(0) do |acc, num| >  sum = acc + num >  puts sum >  sum > end > > Now since 'sum' is the final statement in the block, acc will be sum for the > next iteration. I understand now. Thank you for clarifying that for me. Alex