From: Robert Klemme Date: 2008-05-16T16:18:30+09:00 Subject: Re: Handling of arrays 2008/5/16 Jesús Gabriel y Galán : > On Fri, May 16, 2008 at 8:49 AM, Jesús Gabriel y Galán > wrote: > >> The accumulator then gets updated by >> the result of the block, so the next iteration will be yielded that >> value. > > I have realized that this sentence can be confusing: the accumulator doesn't > get updated. The next value for the accumulator will be the result of the block, > not necesarily the same object. Correct. > I have read many times that you shouldn't use the same accumulator by > applying destructive methods to it, but I can't remember what the pros and > cons were. Do you remember where you read that? > So this should not be done: > > irb(main):012:0> [1,2,3].inject([]) {|total,x| total << x**2} > => [1, 4, 9] > > Instead you should do this: > > irb(main):013:0> [1,2,3].inject([]) {|total,x| total + [x**2]} > => [1, 4, 9] > > Maybe someone can chime in and explain this a little bit better? Sorry, but this is nonsense. It's completely safe and even reasonable to reuse an accumulator value. Your second solution creates new Arrays all the time and then throws them away. It is much more efficient to use Array#<< as in your first example. If, of course the original accumulator value must not be changed because side effects will do harm, then of course you cannot modify it but need to create new objects. But in the scenario above, where the Array is solely created for #inject it is the most reasonable thing to directly append. Kind regards robert -- use.inject do |as, often| as.you_can - without end