[LRUG] Unexpected behaviour of << operator

Marcus Roberts marcus at marcusr.org.uk
Wed Aug 18 08:26:59 PDT 2010


On 18 Aug 2010, at 16:19, Damian Janowski wrote:

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

Sort of.  I understand the difference between += and x = x +

In my understanding

n = p.name

copied the value of p.name into n and at that point it became independent of the original string.

so n = "a new string" wouldn't change the value of p.name

But to make it simpler

>> s1 = "string1"
=> "string1"
>> s2 = s1
=> "string1"
>> s2 << "_extra"
=> "string1_extra"
>> s1
=> "string1_extra"

which is very non-intuitive to me even after programming Ruby for 4 years :-)

It just goes to show how a mental model can be wrong, but takes a particular angle to reveal that!

Marcus









More information about the Chat mailing list