Accessing a Class' instance variable from outside

Hsiu picture Hsiu · Nov 17, 2010 · Viewed 12.8k times · Source

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.

Answer

JellicleCat picture JellicleCat · Mar 30, 2012
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