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
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
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
No, but I feel it should be less than 5 lines:
local_variables.each {|name| puts name + "=" + eval(name).inspect }
Cheers,
Dave