Variable Dump

D

Dan Smorey Jr.

I'd like to know how to grab a dump of all variable associated with a
script. Here is a test script I am using...

#!/usr/bin/env ruby

class Binding
def info_locals()
vars =3D eval("local_variables", self)
vars.each { |v| puts %(#{v} --> #{eval(v, self).inspect}) }
end
end

def foo_def
inside_foo_def =3D "hello there"
binding.info_locals
end

foo =3D 'hello'
bar =3D "goodbye"
array =3D [ 'one', 'two' ]

foo_def()

I get this output...

inside_foo_def --> "hello there"

That's the problem. I do not get all variables, just the variable in
the def foo_def scope. I'd like to be able to grab foo, bar, and
array also, much like this...

inside_foo_def --> "hello there"
foo --> "hello"
bar --> "bar"
array --> ['one', 'two']

Thanks in advance.
 
R

Robert Klemme

Dan Smorey Jr. said:
I'd like to know how to grab a dump of all variable associated with a
script. Here is a test script I am using...

#!/usr/bin/env ruby

class Binding
def info_locals()
vars = eval("local_variables", self)
vars.each { |v| puts %(#{v} --> #{eval(v, self).inspect}) }
end
end

def foo_def
inside_foo_def = "hello there"
binding.info_locals
end

foo = 'hello'
bar = "goodbye"
array = [ 'one', 'two' ]

foo_def()

I get this output...

inside_foo_def --> "hello there"

That's the problem. I do not get all variables, just the variable in
the def foo_def scope. I'd like to be able to grab foo, bar, and
array also, much like this...

inside_foo_def --> "hello there"
foo --> "hello"
bar --> "bar"
array --> ['one', 'two']

Thanks in advance.

You would have to walk up the call stack to get locals of surrounding
environments. Kernel.set_trace_func may help here.

Kind regards

robert
 
L

Lou Vanek

this clumsy script gets you part of the way there.
maybe somebody else knows a recursive solution.


#!/usr/bin/env ruby

$top_level = binding

class Binding
def info_vars(b = self)
vars = eval("local_variables", b)
vars.each { |v| puts %(#{v} --> #{eval(v, b).inspect}) }
end
end

def foo_def
inside_foo_def = "hello there"

binding.info_vars
puts "\n# top level:"
binding.info_vars $top_level
end

foo = 'hello'
bar = "goodbye"
array = [ 'one', 'two' ]
foo_def()
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top