From: Chad Perrin Date: 2007-04-07T23:07:03+09:00 Subject: Re: Everything is a object? On Sat, Apr 07, 2007 at 06:23:50PM +0900, Brian Candler wrote: > On Fri, Apr 06, 2007 at 10:24:58PM +0900, Jamal Soueidan wrote: > > Now the question is, > > > > When does the instance variable holds the object itself? > > Instance variables hold references to what ever object you assigned to them. > > > class A; end; > > > > @one = A.new > > @two = A.new > > > > p @one.object_id > > p @one_object_id > > # 21103660 > > # 21103640 > > > > Two different objects, even if they were the same. > > Perhaps you'd find it helpful if you tried to work out yourself what was > going on - and if you can't, explain your own explanation and why you think > it is wrong. > > But to answer it for you: > > (1) A.new generates a new instance of class A. Every time you invoke A.new > you get a fresh object. Each object has a unique object_id during its > lifetime. > > (2) '@one = A.new' assigns (a reference to) the newly-created object into an > instance variable. Since this assignment is "out in the wild", i.e. not > inside any "class Foo .. end" or "def bar .. end" construct, then you are > assigning to an instance variable of a top-level session object called > 'main' > > A longer way of writing it would have been: > > main.instance_variable_set(:@one, Foo.new) > > Then assigning to @two you'll get another object reference stored there. > > Clearly then, puts @one.object_id and puts @two.object_id will show you > distinct references to the two distinct objects you created. If you want two separate names for the same object with the same object ID (aka the same object_id), you could chain assignments together: irb(main):003:0> three = four = A.new => # irb(main):004:0> three.object_id === four.object_id => true irb(main):005:0> p three.object_id 67285850 => nil irb(main):006:0> p four.object_id 67285850 => nil -- CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ] Leon Festinger: "A man with a conviction is a hard man to change. Tell him you disagree and he turns away. Show him facts and figures and he questions your sources. Appeal to logic and he fails to see your point."