I am curious if as to whether or not it would be possible to loop through the instance variables of an object and dump out some basic debug information.
I know you can get a list of instance variables by doing object.instance_variables which returns an array of symbolized variables like [:@var1, :@var2, :@etc]
My first guess at how to do this was:
obj.instance_variables.each do
obj.instance_variable_get(var).to_yaml
end
but i am getting the following error: "can't dump anonymous class Class". What might a better approach be?
The problem is you have some anonymous proc or function in your instance variables that doesn't respond to to_yaml. Because it can't be converted to yaml you are getting this error. Try using inspect instead, all objects should respond to inspect:
obj.instance_variables.each do |var|
p obj.instance_variable_get(var).inspect
end
You have to take into account that in ruby just declaring the attr_accessor will not create the variable, you need to assign it:
class A
attr_accessor :x, :y
def initialize(z)
@x=z
end
end
def inspect_object(o)
o.instance_variables.each do |var|
var.slice!(0)
p var
p o.send(var)
end
end
a = A.new(5)
inspect_object(a)
This outputs
"x"
5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.