From: "Jesús Gabriel y Galán" Date: 2010-04-22T02:00:00+09:00 Subject: Re: Bug? variable changes without assignment On Wed, Apr 21, 2010 at 6:26 PM, Bob Gustafson wrote: > Jesús Gabriel y Galán wrote: > >> This is not a bug, it's the way objects and variables work in ruby. >> When you do this: >> >> variable = constant >> >> you are saying that variable now references the same object that >> constant references. So any message sent through variable or constant >> is sent to the same string object. If that message is a destructive >> message (like []=, or <<, or sub!), the object is changed and both >> variables will see the change since they are referencing the same >> object. >> > > Ok, good to know that it is not a bug. > > However, what is the syntax for an assignment where variable and > constant do NOT refer to the same object? Then what object do you want the second variable to refer to? If you want a duplicate of the object: variable = constant.dup is a usual idiom. Be careful when you deal with arrays this way, because an array is just a bunch of references, so even if you dup the array, the objects contained will be the same ones (dup performs a shallow copy). Jesus.