From: "Jesús Gabriel y Galán" Date: 2010-04-22T00:47:37+09:00 Subject: Re: Bug? variable changes without assignment On Wed, Apr 21, 2010 at 5:37 PM, Bob Gustafson wrote: > I seem to have uncovered a bug. The program below defines a series of > variables, named constant, modify, and variable. The constant should > remain constant, but instead, it changes - even without an assignment. > How does this happen? > > [root@hoho4 ocr]# cat test.rb >    constant = '31.12.2006' > puts "constant " + constant >    modify = '40.01' > puts "modify " + modify > >   variable = constant > > puts "variable " + variable > puts "constant " + constant puts variable.object_id puts constant.object_id >   variable[0..1] = modify[0..1] This sends the message []= to the string object, which modifies the string object contents. > puts "variable " + variable > puts "constant " + constant > > > [root@hoho4 ocr]# ruby test.rb > constant 31.12.2006 > modify 40.01 > variable 31.12.2006 > constant 31.12.2006 > variable 40.12.2006 > constant 40.12.2006    <<<---- Why does this change??? 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. Check this simpler example irb(main):001:0> class A irb(main):002:1> attr_accessor :a irb(main):003:1> def initialize value irb(main):004:2> @a = value irb(main):005:2> end irb(main):006:1> end => nil irb(main):008:0> a = A.new "original value" => # irb(main):009:0> b = a => # At this point a and b reference the same object. irb(main):010:0> a.a = "different value" => "different value" irb(main):011:0> a => # irb(main):012:0> b => # so modifying the object through a means that we modify the same object referenced by b, because there's only one object. Hope this clarifies, Jesus.