From: dblack@... Date: 2006-11-15T22:08:17+09:00 Subject: Re: Design problem with 'inject' On Wed, 15 Nov 2006, Gary Boone wrote: > > Those are several good suggestions. > > next sum if (i == 3) > > strikes me as simple and clear. Provided you know that the block result > is what matters, you can stay out of trouble. I think you're well advised to know that if you're using inject :-) > Simplifying the example, the trouble with inject is that > > arr.inject(0) { |sum, i| sum += i } > arr.inject(0) { |sum, i| sum + i } > > both produce the same result. Yuk. > > Maybe it should be posted somewhere as a potential 'gotcha'. It's not, though; it's just how Ruby works. When you do: sum += i the parser turns it into: sum = sum + i So you're just reusing the identifier 'sum'. As with all reassignment, the variable is completely reinitialized. David -- David A. Black | dblack@rubypal.com Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org