Below is my code with class MyClass and class OtherClass, which inherits MyClass. I have a class variable @@my_new_var and a class instance variable @my_var.
class MyClass @@my_new_var = "test" @my_var = 1 def self.read; @my_var end def ins_method; @my_var = 2 end end class OtherClass < MyClass def self.read_another; @@my_new_var end def self.test; @my_var end end We can access class variables from a subclass:
OtherClass.read_another # => test but we can't access class instance variables from a subclass:
MyClass.read # => 1 MyClass.new.ins_method # => 2 OtherClass.read # => nil OtherClass.test # => nil Why is that? What is the scope of class instance variables?
@my_varthat appears indef ins_method; @my_var = 2 endis not a class instance variable.class Klass; @cat = "meow"; def cat; self.class.instance_variable_get(:@cat); end; end. ThenKlass.new.cat => "meow".