Class variables in Ruby

D

dblack

Hi --

Smalltalk has pretty much the same thing, there's a difference between
class variables which are shared by the class and it's subclasses, and
are traditionally implemented by binding an association between the
name and value into compiled methods, and class instance variables
which are instance variables of the class object, and are implemented
as instance variable slots in the class objects, so every subclass has
it's own value. It's been awhile, and there are Smalltalk dialect
differences but these get declared in messages to the classes subclass
something like:

Object subclass: #Foo ...
instanceVariables: 'a b'
classVariables: 'C1 C2'
classInstanceVariables: 'ci1 ci2'

We also worked on a completely declarative model for class definition
in Smalltalk in X3J20, but I don't know if anyone picked it up.

In Ruby these are defined as they are encountered in execution and
marked with sigils, @ for instance and class variables, and @@ for
class variables, the difference between instance and class instance
variables being WHERE they are encountered.

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 :) and (b) focus on 'self'. If self
changes, then the owner of @var changes.


David

--
http://www.rubypowerandlight.com => Ruby/Rails training & consultancy
----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <-----
http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log
http://www.manning.com/black => book, Ruby for Rails
http://www.rubycentral.org => Ruby Central, Inc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top