dynamically read object's attributes

M

Mark Pelletier

I want to read the values of instance variables in an object, but I
don't know how to reach them. I think the code should be something
like:

def read_stuff
s = "Class: #{self.class}:\n"
s += "Instance variables:\n"
self.instance_variables.each do
|var|
s += "#{var}: #{SOMETHING}\n"
end
s += "\n"
end

But I don't know what to replace SOMETHING with. Anyone know?
 
S

Stefano Crocco

Alle venerd=C3=AC 21 settembre 2007, Mark Pelletier ha scritto:
I want to read the values of instance variables in an object, but I
don't know how to reach them. I think the code should be something
like:

def read_stuff
s =3D "Class: #{self.class}:\n"
s +=3D "Instance variables:\n"
self.instance_variables.each do

|var|

s +=3D "#{var}: #{SOMETHING}\n"
end
s +=3D "\n"
end

But I don't know what to replace SOMETHING with. Anyone know?

instance_variable_get var

Stefano
 
T

Tim Hunter

Mark said:
I want to read the values of instance variables in an object, but I
don't know how to reach them. I think the code should be something
like:

def read_stuff
s = "Class: #{self.class}:\n"
s += "Instance variables:\n"
self.instance_variables.each do
|var|
s += "#{var}: #{SOMETHING}\n"
end
s += "\n"
end

But I don't know what to replace SOMETHING with. Anyone know?

Object#instance_variable_get
 
J

Jano Svitok

I want to read the values of instance variables in an object, but I
don't know how to reach them. I think the code should be something
like:

def read_stuff
s = "Class: #{self.class}:\n"
s += "Instance variables:\n"
self.instance_variables.each do
|var|
s += "#{var}: #{SOMETHING}\n"
end
s += "\n"
end

But I don't know what to replace SOMETHING with. Anyone know?

instance_variable_get(var)

You might want to read rdoc for Object and Module for more similar
interesting methods.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top