[LRUG] Unexpected behaviour of << operator

Damian Janowski djanowski at dimaion.com
Wed Aug 18 08:19:44 PDT 2010


On Wed, Aug 18, 2010 at 12:15 PM, Marcus Roberts <marcus at marcusr.org.uk> wrote:
> I've just been chasing down a weird bug, the cause of which was accidentally using << instead of =

Nothing to do with ActiveRecord. In the first case you're creating a
new variable pointing to the same string object as p.name. Then, when
you do:

n += "_extra"

Is equivalent for:

n = n + "_extra"

In that case, n is pointing to a new string which is the result of
adding n and "_extra". No modification is made to the string that n
was pointing to before.

In the second case, you're concatenating to the string object to which
both n and p.name are pointing. Thus it's modified 'everywhere'.

Makes sense?



More information about the Chat mailing list