From: Jonathan Nielsen Date: 2010-06-15T23:31:13+09:00 Subject: Re: Unexpected behavior in inject --00c09fa2176fd163930489127410 Content-Type: text/plain; charset=UTF-8 > [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. -Jonathan Nielsen --00c09fa2176fd163930489127410--