0

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?

3
  • The @my_var that appears in def ins_method; @my_var = 2 end is not a class instance variable. Commented Sep 28, 2014 at 13:41
  • yeah I knew that, class instance variables can be accessed in class methods only if i'm not wrong. Commented Sep 28, 2014 at 13:45
  • 1
    Class instance variables can be accessed by instances using Object#instance_variable_get; e.g., class Klass; @cat = "meow"; def cat; self.class.instance_variable_get(:@cat); end; end. Then Klass.new.cat => "meow". Commented Sep 28, 2014 at 22:00

1 Answer 1

2

Q1: Because they are defined so.

Q2: It is the class (which is an instance of the Class class).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.