Search code examples
rubyirb

How to run IRB.start in context of current class


I've been just going through PragProg Continuous Testing With Ruby, where they talk about invoking IRB in context of current class to inspect the code manually.

However, they quote that if you invoke IRB.start in a class, self is predefined, and refers to the object we were in when start was called which isn't true in my case.

Even for very simple example like

a = "hello"
require 'irb'
ARGV.clear # otherwise all script parameters get passed to IRB
IRB.start

When I try to access the a variable, I get the obvious

NameError: undefined local variable or method `a' for main:Object

It works only when I change a to global variable

$a = "hello"
require 'irb'
ARGV.clear # otherwise all script parameters get passed to IRB
IRB.start

then I can access it

irb(main):001:0> $a
=> 1

Is there any way around this to access local and instance variables in the current class?


Solution

  • I'd suggest trying this in ripl, an irb alternative. The above example works:

    a = 'hello'
    require 'ripl'
    Ripl.start :binding => binding
    

    Note that local variables work because your passing the current binding with the :binding option.

    You could possibly do the same in irb, but since it's poorly documented and untested, your chances of doing it cleanly are slim to none.