From: Brian Candler Date: 2007-04-07T18:23:50+09:00 Subject: Re: Everything is a object? 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. Try also: puts main.inspect puts main.instance_variables However unless you're just playing around in irb, nobody creates instance variables inside 'main'. You normally create them within an object of your own. Brian.