Display instance variable values

If I have a people class with instance variables @name @age and @gender
and an instance of that class called peep (justa an example).
If I want to see all the available instance variables I can do:

p peep.instance_variables => ["@age", “@name”, “@gender”]

Is there a way to get the value of those instance variables for the peep
instance without calling a class method ? Say there is full r/w access
to the instance variables.

Something like:

peep.instance_variables.each do |var|

var.(display value somehow)

end

Thanks.

Try using instance_variable_get:

p peep.instance_variables # => ["@age", “@name”, “@gender”]

peep.instance_variables.each do |var|
p var.instance_variable_get var
end

That won’t work.
Your asking an instance variable (var) to show its instance variables.
Tried it just to be sure.

On Sat, Nov 13, 2010 at 11:08 PM, John S. [email protected]
wrote:

Something like:

peep.instance_variables.each do |var|

var.(display value somehow)

end

What are you trying to do? This seems a little strange to me.

In any case, if the instance variable are readable or accessible, i.e.
defined with attr_reader, attr_accessor, or have methods to get them,
you can use send to get at their values:

peep.instance_variables.each do |var|
puts peep.send(var.sub(‘@’, ‘’))
end

Again, it feels a little strange to me.

HTH,
Ammar

On Sat, Nov 13, 2010 at 3:08 PM, John S. [email protected]
wrote:

Something like:
Thanks.


Posted via http://www.ruby-forum.com/.

replace the line “var.(display value somehow)” with “puts
peep.instance_variable_get(var)”

On Sat, Nov 13, 2010 at 11:42 PM, Josh C. [email protected]
wrote:

replace the line “var.(display value somehow)” with “puts
peep.instance_variable_get(var)”

Ah. I forgot about that one.

Thanks,
Ammar

Not trying to do anything other than experiment. I was playing with for
the first time today and the book I’m readin said the view had access to
the controller’s instance variables. I was trying to find out what other
instance variables/values the view could access. in the erb file id put
this code in:
<% self.instance_variables.each do |var| %>
<%= h(var) %>
<%end%>

And it gave me a list of the instance variables without values… just
trying to learn by experimenting.