Class variables in Ruby

Hi –

On Mon, 21 Aug 2006, Rick DeNatale wrote:

Smalltalk has pretty much the same thing, there’s a difference between
instanceVariables: ‘a b’

In Smaltalk, class variables are in the scope of both class and
methods of the class which declares them, and its subclasses.
Instance variables are visible in methods of the class and it’s
subclasses, and class instance variables to class methods of the class
and it’s subclasses. This the same as in Ruby.

The class and its subclasses are different objects, though, so they
don’t share instance variables. For example:

class C
@a = 1
end

class D < C
puts @a # nil
end

D’s @a is not the same as C’s @a. It’s true that if C defines a
class method that does something with @a, D will also be able to call
that method – but the two @a’s themselves don’t have any connection
to each other. That’s different from class variables, where the
subclass’s ones are actually the same as the superclass’s – usually,
but not always, and maybe not in Ruby 2… (It’s also the only
example I know of where a singleton method defined on one object can
be called on another.)

I think the best way to think of instance variables in Ruby is (a)
forget about class variables :slight_smile: and (b) focus on ‘self’. If self
changes, then the owner of @var changes.

David