Hi --

On Sat, 26 Nov 2005, Ross Bamford wrote:

> Hi folks.
>
> I'm getting on really well with Ruby (I've not enjoyed programming this much 
> for ages :)) but I've a few (probably simple) questions I'm hoping you might 
> be able to help with.

Let me zero in on one of your questions (I'm sure you'll get multiple
replies :-)

> 3) Does this
>
> 	class MyClass
> 	  @field = "one"
>     end
>
> create a class or instance variable?

@var is always an instance variable; @@var is always a class variable.
Let me stick to the former.

There's a simple way to get a handle on instance variables:

At every moment during runtime, there is a current or default object
-- "self".  Every time you see:

   @var

you are seeing an instance variable that belongs to "self", the
current object.  There's never any ambiguity.

"self", in turn, can be any object, including a Class object.  So,
when in doubt, ask what "self" is:

   class C
     puts "In class definition body scope"
     puts self                             # C (the class object)
     @var = 1
     puts @var                             # 1

     def some_method
       puts "In instance method scope"
       puts self                       # an instance of C
       puts @var                       # nil
     end
   end

   c = C.new
   c.some_method

As you'll see from the output, the fact that the object C (the Class
object) assigns to its instance variable @var does not affect the @var
of an *instance* of C (which is uninitialized and therefore nil).

You can think of class objects as wearing two hats: the "special case"
hat of being an object factory, and the "civilian" hat of just being
an object.  It's in "civilian" mode that class objects possess
instance variables of their own, on the same footing as all other
objects.


David

-- 
David A. Black
dblack / wobblini.net