Accessing instance variables in Ruby

Classes may have instance variables that are not explicitly in the public interface – this is, they don’t have a corresponding reader method. These variables can still be accessed with instance_variable_get, a method of Object class. Consider the following example:


If we make an instance of Example and call #name, we’ll get a NoMethodError, since there is actually no name method.

We can get the value of @name with instance_variable_get:

The returned value will be that of the current state of the variable when we retrieve it:

December 25, 2014