IRB is a nice way to play around and test things in Ruby. It’s also possible to do some setup using a script, like this:
require 'irb'
class Pirate
def greet
puts "Arrrrr, nice to meet ya"
end
end
IRB.start # You can now instantiate Pirate in IRB
One thing I’m unclear on, however, is variable scope when doing this. If I add these lines before IRB.start:
smithy = Pirate.new
@blackbard = Pirate.new
… @blackbeard will be available in IRB, but referencing smithy will get undefined local variable or method 'smithy' for main:Object.
Why?
The
Bindingthat is used to evaluate the code is set up inirb/workspace.rb:51(I’m referring to Ruby 1.9.3 rev 35410 here):That means that your IRB session runs in the same context as code inside a top-level method. Observe:
Output:
Note that the object context (
self) is the same both inside and outside the function. This is because every top-level method is added to the globalmainobject.Also note that the bindings inside and outside of the method differ. In Ruby, every method has its own name scope. This is why you can’t access the local name from inside IRB, while you can access the instance variable.
To be honest, IRB is not the most glorious piece of Ruby software. I usually use Pry for this kind of stuff, using which you can just do:
And have a session with access to the current local variables.