Forum: Ruby Variable Dump

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
1a5308cf823e320bced9f0cfed49ba33?d=identicon&s=25 Dan Smorey Jr. (Guest)
on 2005-12-27 21:45
(Received via mailing list)
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.
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2005-12-27 22:40
(Received via mailing list)
Dan Smorey Jr. <dsmorey@gmail.com> wrote:
>   end
> foo_def()
> 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
Ce60c4f78a63b0695e4dafc4bd7964f7?d=identicon&s=25 Lou Vanek (Guest)
on 2005-12-28 00:58
(Received via mailing list)
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()
This topic is locked and can not be replied to.