[LRUG] Unexpected behaviour of << operator

Damian Janowski djanowski at dimaion.com
Wed Aug 18 08:39:33 PDT 2010


On Wed, Aug 18, 2010 at 12:26 PM, Marcus Roberts <marcus at marcusr.org.uk> wrote:
> 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

No, not exactly. By doing n = p.name you're simply creating a new
variable pointing to the same underlying string object. If you do n =
"new string", again you're changing n to point to a new string,
without touching the original underlying string object.

But when you use concat, you're telling Ruby to expand the underlying
string object to accommodate the extra characters you're giving it
(similar to how String#sub! will modify the receiver, for example, or
a method in any class that modifies its internal state versus
returning a new object with the result of the operation).

As you say, you probably get all this with other types of objects, but
probably were giving strings a special, undeserved treatment.

Hope that helped.



More information about the Chat mailing list