Get top-level namespace in Ruby
How can I do this in Ruby?:
Sometimes for diagnostics in interpreted language, it's faster for me to make a quick alteration开发者_Python百科 to my code, tossing an object into the top-level namespace, then mess with it there in an interactive environment.
In Python, I add this to my code:
import __main__
__main__.[field] = [my problematic object]
...then run the file with a command python -i [myfilename]
. Any idea how I can get access to the top-level namespace in Ruby?
I'd recommend using Pry for this.
Run gem install pry
to install pry. Then add the following code where you want to start an interactive session.
require 'pry'
binding.pry
An example of an interactive session.
$ cat debug.rb
a = 7
b = 6
product = a * b
require 'pry'
binding.pry
puts "The answer is: #{product}"
$ ruby debug.rb
From: debug.rb @ line 5 in Object#N/A:
1: a = 7
2: b = 6
3: product = a * b
4: require 'pry'
=> 5: binding.pry
6: puts "The answer is: #{product}"
pry(main)> product
=> 42
pry(main)> product = -1 * a * b
=> -42
pry(main)> exit
The answer is: -42
精彩评论