Assignment as a reference?

Hi,

I ran into a simple issue earlier with assignment seeming to make
references. I’m new to Ruby so perhaps this is how it’s supposed to be.
Here
is an abridged version of what happened:

foo = ‘bar’ #=> bar
foo2 = foo #=> bar
foo = foo.gsub ‘bar’, ‘wibble’ #=> wibble
foo2 #=> bar

foo = ‘bar’ #=> bar
foo2 = foo #=> bar
foo.gsub! ‘bar’, ‘wibble’ #=> wibble
foo2 #=> wibble

You can paste those straight into irb and get the same output. Could
someone
please explain why the second example changes foo2?

Cheers,
Morgan G…

Hi –

On Tue, 21 Aug 2007, Morgan G. wrote:

Hi,

I ran into a simple issue earlier with assignment seeming to make
references. I’m new to Ruby so perhaps this is how it’s supposed to be. Here

It is.

foo2 #=> wibble

You can paste those straight into irb and get the same output. Could someone
please explain why the second example changes foo2?

Ruby assignments pretty much traffic in references. When you do:

foo2 = foo

you’re giving foo2 a copy of the reference that foo contains. When you
change the object, you see the change reflected through any reference
to it.

David

On 20 Aug 2007, at 17:20, Morgan G. wrote:

foo = ‘bar’ #=> bar
foo2 = foo #=> bar
foo.gsub! ‘bar’, ‘wibble’ #=> wibble
foo2 #=> wibble

What you have experienced is reference assignment. If you wish to
duplicate only the content, and not the reference, then you should to
use .dup.

foo = “bar”
=> “bar”
foo2 = foo.dup
=> “bar”
foo = “wibble”
=> “wibble”
foo2
=> “bar”

Hope this helps you out.

Douglas F Shearer
[email protected]

Thanks for that.

I’ve been reading through quite a few references and manuals (working
through Agile Web D. at the moment) and the fact that every
assignment is a reference hasn’t really been mentioned that much. Guess
I’ve
missed it or haven’t gotten that far.

Cheers.