2

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?

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Depending on what sort of object you're talking about, you might be able to get everything you need just with obj.inspect (?).
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.