Konstantin
Konstantin

Reputation: 3123

How can I use irb the Ruby interpreter to test/debug my .rb files?

How can I use irb the Ruby interpreter to test/debug my .rb files? I want to load an .rb file, let it run, and after it ends, get back to the irb prompt so I would be able to manipulate the variables which my script has built.

I tried load, require, and irb -r, but none of them worked as I would like. After the execution, when the program terminates, I get an irb prompt, but all of the variables are inaccessible. What can I do?

Upvotes: 0

Views: 1531

Answers (5)

Eric Mathison
Eric Mathison

Reputation: 1256

binding.irb

As of Ruby 2.4, placing this in your code will drop you into an irb session in the scope where it is placed.

No additional gem installs or require statements are needed.

Upvotes: 0

horseyguy
horseyguy

Reputation: 29915

  1. Install the pry gem see: http://pryrepl.org
  2. require 'pry' at the start of your program.
  3. put binding.pry at the end of your program (or where you want to start the interactive session)
  4. run your program.

Using pry you will have all your variables in scope.

More information see the link above, and here:

http://banisterfiend.wordpress.com/2011/01/27/turning-irb-on-its-head-with-pry/

and:

https://github.com/pry/pry/wiki/Runtime-invocation

Upvotes: 2

Sigurd
Sigurd

Reputation: 7953

Add following code in place where you want irb to start

require 'irb'
IRB.start(__FILE__)

Upvotes: 0

redgetan
redgetan

Reputation: 953

Not sure exactly what you want to do, but it sounds like you may want to use the "pry" gem instead.

Upvotes: 2

sawa
sawa

Reputation: 168239

If the variables you want are local variables, I do not think there is a way you can access them from another file.

If you just want the return value of the whole code that is on a different file, you can eval the whole content of that file within the main code and access the return value. You can access multiple values by putting them in an array or a hash at the end of the file to be evaled.

Upvotes: 0

Related Questions