Can anyone tell me about the difference between class variables and class instance variables?
A class variable (@@
) is shared among the class and all of its descendants. A class instance variable (@
) is not shared by the class's descendants.
Class variable (@@
)
Let's have a class Foo with a class variable @@i
, and accessors for reading and writing @@i
:
class Foo
@@i = 1
def self.i
@@i
end
def self.i=(value)
@@i = value
end
end
And a derived class:
class Bar < Foo
end
We see that Foo and Bar have the same value for @@i
:
p Foo.i # => 1
p Bar.i # => 1
And changing @@i
in one changes it in both:
Bar.i = 2
p Foo.i # => 2
p Bar.i # => 2
Class instance variable (@
)
Let's make a simple class with a class instance variable @i
and accessors for reading and writing @i
:
class Foo
@i = 1
def self.i
@i
end
def self.i=(value)
@i = value
end
end
And a derived class:
class Bar < Foo
end
We see that although Bar inherits the accessors for @i
, it does not inherit @i
itself:
p Foo.i # => 1
p Bar.i # => nil
We can set Bar's @i
without affecting Foo's @i
:
Bar.i = 2
p Foo.i # => 1
p Bar.i # => 2