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