Variable value "dump"

B

Brian Takita

Hello,

Is there a way to loop through and display all of the local variable
symbols and values in a function?

I would like to use this to log exceptions.

Thank you,
Brian Takita
 
B

Brian Takita

It looks like there is a Kernal.local_variable method that returns an
Array of the local variable names.

So I can print out the local variables with their values this way. Is
there a way to do this without using eval?

a = 1

local_variables.each do |vn|
val = ''
eval("val=#{vn}")
print "#{vn}=#{val}"
end
 
R

Robert Klemme

Brian Takita said:
It looks like there is a Kernal.local_variable method that returns an
Array of the local variable names.

So I can print out the local variables with their values this way. Is
there a way to do this without using eval?

I don't think so.
a = 1

local_variables.each do |vn|
val = ''
eval("val=#{vn}")
print "#{vn}=#{val}"
end

Here are some variants

local_variables.each do |vn|
print "#{vn}=#{eval vn}\n"
end

var_dump = local_variables.inject "" do |dump,vn|
dump << vn << "=" << eval(vn).inspect << "\n"
end

Alternatively you can put a binding into the exception that can be used to
retrieve variable values when needed. Semantics are a bit differnt though
(i.e. values might change between the time when the exception is thrown and
the evaluation). Example:

class MyError < Exception
def initialize(msg, bnd)
super(msg)
@bnd = bnd
end

def dump_var
eval("local_variables", @bnd).inject "" do |dump,vn|
dump << vn << "=" << eval(vn, @bnd).inspect << "\n"
end
end
end


def foo(args={})
bar = "hello"
raise MyError.new "something wrong", binding
end

begin
foo:)x => :u, :name => "nonsense", :numbers => [1,5,67])
rescue MyError => e
puts e, "variables:", e.dump_var
end

Prints

something wrong
variables:
args={:x=>:u, :numbers=>[1, 5, 67], :name=>"nonsense"}
bar="hello"


Kind regards

robert
 
D

Dave Burt

Brian Takita wrote...
Is there a way to do this without using eval?
...

No, but I feel it should be less than 5 lines:

local_variables.each {|name| puts name + "=" + eval(name).inspect }

Cheers,
Dave
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top