On Fri, May 16, 2008 at 9:18 AM, Robert Klemme
<shortcutter / googlemail.com> wrote:
> 2008/5/16 Jes Gabriel y Gal <jgabrielygalan / gmail.com>:

>> 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?

No, I probably misunderstood something.

>> 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.

Yep, I saw that and that's why I refused to even try to explain it :-)

> 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.

This might be what I had in mind.

> But in the scenario above, where the
> Array is solely created for #inject it is the most reasonable thing to
> directly append.

It's clear that the example injecting a newly created array makes the
above explanation even worse :-).

Thanks !

Jesus.