There’s been a lot of blog traffic lately about class variables vs.
class instance variables.
I’d like to give an example of something in-between: class-tree
variables. These are sort
of like class variables, but they only point downward in the
inheritance tree rather than
up. That is, each class in an inheritance tree can get a variable
which refers to itself and
all its descendents. Class-tree variables are implemented by class
variables, but the
implementation occurs only in the top (root) class and is inherited by
the rest of the tree.
It is probably unclear what the heck I am talking about, but the
following example should
make things clear.
class_tree_var.rb: demo program of class-tree variables
#-- Hey Emacs! Use -- mode: ruby; coding: utf-8-unix; --
class Person
attr_accessor :name
class << self
attr_writer :instances
def instances
@instances ||= []
end
end
def initialize( name )
klass = self.class
until klass == Person
klass.instances << self
klass = klass.superclass
end
Person.instances << self
@name = name
end
end
class Scholar < Person
end
class Student < Scholar
end
class Professor < Scholar
end
%w(Fred Barney).each{|caveman| Person.new(caveman)}
%w(Wilma Betty).each{|cavewoman| Scholar.new(cavewoman)}
%w(Twerply Bob Sheila).each{|brat| Student.new(brat)}
%w(Whiplash Grindemdown).each{|sadist| Professor.new(sadist)}
puts "Persons are " + Person.instances.collect{|person|
person.name}.join(’, ‘)
puts "Scholars are " + Scholar.instances.collect{|scholar|
scholar.name}.join(’, ‘)
puts "Students are " + Student.instances.collect{|student|
student.name}.join(’, ‘)
puts "Professors are " + Professor.instances.collect{|professor|
professor.name}.join(’, ')
end of file
$ ruby class_tree_var.rb
Persons are Fred, Barney, Wilma, Betty, Twerply, Bob, Sheila,
Whiplash, Grindemdown
Scholars are Wilma, Betty, Twerply, Bob, Sheila, Whiplash, Grindemdown
Students are Twerply, Bob, Sheila
Professors are Whiplash, Grindemdown
I don’t actually recommend this. I think that in Ruby it’s better not
to use inheritance for
such things; you have an abundance of alternatives that are more
flexible. Functionality
built into inheritance tends to break upon refactoring. But I think
this example does shed
some light on what class instance variables are capable of. It did
for me, anyway.
Regards, Bret
Bret Jolly