Ruby – Accessing a Class’ instance variable from outside

class-variablesinstance-variablesrubyvariables

I understand (I think) the difference between class variables and instance variables of a class in Ruby.

I'm wondering how one can access the instance variables of a class from OUTSIDE that class.

From within (that is, in a class method instead of an instance method), it can be accessed directly, but from outside, is there a way to do MyClass.class.[@$#]variablename?

I don't have any specific reason for doing this, just learning Ruby and wondering if it is possible.

Best Answer

class MyClass

    @my_class_instance_var = "foo"

    class << self
        attr_accessor :my_class_instance_var
    end

end

puts MyClass::my_class_instance_var

The foregoing yields:

>> foo

I believe that Arkku demonstrated how to access class variables (@@), not class instance variables (@) from outside the class.

I drew the foregoing from this essay: Seeing Metaclasses Clearly