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 Grubb.
Hi --
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.
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?
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 Tue, 21 Aug 2007, Morgan Grubb wrote:
--
* Books:
RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242\)
RUBY FOR RAILS (http://www.manning.com/black\)
* Ruby/Rails training
& consulting: Ruby Power and Light, LLC (http://www.rubypal.com)
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
dougal.s@gmail.com
···
On 20 Aug 2007, at 17:20, Morgan Grubb wrote:
Thanks for that.
I've been reading through quite a few references and manuals (working
through Agile Web Development 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.
···
On 20/08/07, Douglas F Shearer <dougal.s@gmail.com> wrote:
On 20 Aug 2007, at 17:20, Morgan Grubb 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
dougal.s@gmail.com
http://douglasfshearer.com