Gary Wright
2/26/2009 8:28:00 PM
On Feb 26, 2009, at 2:59 PM, Chris Gardner wrote:
> What I mean is that I would like to ask a class for the names of
> instance variables of its objects, which may have yet to be
> instantiated.
The question doesn't apply in Ruby since instance variables are
dynamically created on a per object basis. Even if you use standard
helpers such as attr_accessor and company, those methods simply create
instance methods that manipulate instance variables--they don't
actually create the instance variables.
Just to be clear, there is no language-supported way to introspect a
Ruby class and determine what instance variables may or may not be
supported by all instances of an object. You can't even introspect to
find out what methods were created by the attr* family of methods and
what methods were simply defined explicitly. Sure you could come up
with heuristics such as:
If there is a method called x and another called x= then there is
probably an instance variable named @x.
But that is just a guess, not something supported by the language
semantics.
The idea that each instance of a class can have its own behavior and
state that is independent of its class definition and that can evolve
over time is something that must be understood before a programmer can
fully grasp Ruby's programming and object model.
Gary Wright