First, in ruby1.8, class variables are shared by all subclasses and parent classes, and you can look at the following code:
class IntelligentLife
@@home_planet = nil
def self.home_planet
@@home_planet
end
def self.home_planet=(x)
@@home_planet = x
end
#...
end
class Terran < IntelligentLife
@@home_planet = "Earth"
end
class Martian < IntelligentLife
@@home_planet = "Mars"
end
p IntelligentLife.home_planet
p Terran.home_planet
p Martian.home_planet
You can see that the results are the same. This is because the class variables of the parent class are shared by the entire inheritance system.
Here, if we want to get the results we need, we're going to use class instance variables, because class instance variables are strictly per-class. Rather than being shared by the entire inheritance system.
class IntelligentLife
@home_planet = nil
class << self
attr_accessor :home_planet
end
end
class Terran < IntelligentLife
@home_planet = "Earth"
end
class Martian < IntelligentLife
@home_planet = "Mars"
end
p IntelligentLife.home_planet
p Terran.home_planet
p Martian.home_planet