class variables, class instance variables and instance variables in ruby
by MichaĆ Kuklis on 13/01/2010This was covered multiple times already. I’ve created this little snippet to remember the difference between different types of variables in ruby:
class A
@@foo = "class variable of the class A"
@foo = "class instance variable of the class A"
def instance_method
@foo = "instance variable of the class A"
end
def self.class_method1
# class variables are visible to and shared by the instance and class methods
@@foo
end
def self.class_method2
# class instance variables are visible to and shared by the class methods
@foo
end
end
p A.new.instance_method # instance variable of the class A
p A.class_method1 # class variable of the class A
p A.class_method2 # class instance variable of the class A
class B < A
@@foo = "class variable of the class B"
@foo = "class instance variable of the class B"
end
p B.class_method1 # class variable in B
# class variable in A is overwritten by one in B !!!
p A.class_method1 # class variable in B
p B.class_method2 # class instance variable of the class B
# class instance variable in A is NOT overwritten by one in B !!!
p A.class_method2 # class instance variable of the class A
@@foo = "class variable of the class A"
@foo = "class instance variable of the class A"
def instance_method
@foo = "instance variable of the class A"
end
def self.class_method1
# class variables are visible to and shared by the instance and class methods
@@foo
end
def self.class_method2
# class instance variables are visible to and shared by the class methods
@foo
end
end
p A.new.instance_method # instance variable of the class A
p A.class_method1 # class variable of the class A
p A.class_method2 # class instance variable of the class A
class B < A
@@foo = "class variable of the class B"
@foo = "class instance variable of the class B"
end
p B.class_method1 # class variable in B
# class variable in A is overwritten by one in B !!!
p A.class_method1 # class variable in B
p B.class_method2 # class instance variable of the class B
# class instance variable in A is NOT overwritten by one in B !!!
p A.class_method2 # class instance variable of the class A
There is 1 comment in this article: