[LRUG] Unexpected behaviour of << operator

Tim Cowlishaw tim at timcowlishaw.co.uk
Wed Aug 18 09:46:47 PDT 2010


Object#object_id is useful to aid understanding of this sort of thing:

ruby-1.8.6-p399 > a = "foo"
 => "foo"
ruby-1.8.6-p399 > a.object_id
 => 2160234320
ruby-1.8.6-p399 > a << "bar"
 => "foobar"
ruby-1.8.6-p399 > a.object_id
 => 2160234320 #the same instance as above
ruby-1.8.6-p399 > a += "baz"
 => "foobarbaz"
ruby-1.8.6-p399 > a.object_id
 => 2160201580 # a different one!

I don't know much C, but as i understand it, the variable name acts
like a pointer: var += "baz" - it instantiates a new string instance,
containing the concatenation of the string that var points to and the
string given in the argument, then updates var to point at it. By
contrast, var << "baz" contactenates "baz" onto the end of the string
pointed to by var.

Hope this is useful,

Tim





On Wed, Aug 18, 2010 at 4: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 =
>
> But this led me to try and work out how an ActiveRecord object field was updating
>
> A simple example:
>
>>> p = Project.find 1
> => #<Project id: 1, user_id: 1, name: "A project name", ...>
>>> n = p.name
> => "A project name"
>>> n += "_extra"
> => "A project name_extra"
>>> p.name
> => "A project name"
>
> but
>
>>> p = Project.find 1
> => #<Project id: 1, user_id: 1, name: "A project name", ...>
>>> n = p.name
> => "A project name"
>>> n << "_extra"
> => "A project name_extra"
>>> p.name
> => "A project name_extra"
>
> I suspect this is something to do with clever overloading of <<  or my complete mis-understanding of something fundamental, but does anyone know why the change gets passed back through when I expected the original variable n to be a value, and not a reference
>
> Marcus
>
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>



More information about the Chat mailing list