Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Variable value "dump"

16 views
Skip to first unread message

Brian Takita

unread,
Aug 26, 2005, 5:32:52 PM8/26/05
to
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

Brian Takita

unread,
Aug 26, 2005, 6:12:56 PM8/26/05
to
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

Robert Klemme

unread,
Aug 27, 2005, 11:44:49 AM8/27/05
to
Brian Takita <brian....@gmail.com> wrote:
> 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

Dave Burt

unread,
Aug 27, 2005, 11:51:14 AM8/27/05
to
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


0 new messages