How to debug Ruby scripts

Use Pry (GitHub).

Install via:

$ gem install pry
$ pry

Then add:

require 'pry'; binding.pry

into your program.

As of pry 0.12.2 however, there are no navigation commands such as next, break, etc. Some other gems additionally provide this, see for example pry-byebug.


  1. In Ruby:

    ruby -rdebug myscript.rb 
    

    then,

    • b <line>: put break-point
    • and n(ext) or s(tep) and c(ontinue)
    • p(uts) for display

    (like perl debug)

  2. In Rails: Launch the server with

    script/server --debugger
    

    and add debugger in the code.


As banister recommended: use pry! I can only agree on this.

pry is a much better repl than irb.

You need to add

require 'pry'

to your source file and then insert a breakpoint in your source code by adding

binding.pry

at the place where you want to have a look at the things (this is like triggering a breakpoint in a classic IDE environment)

Once your program hits the

binding.pry

line, you'll be thrown right into the pry repl, with all the context of your program right at hand, so that you can simply explore everything around, investigate all objects, change state, and even change code on the fly.

I believe you can not change the code of the method that you are currently in, so you can sadly not change the next line to be executed. But good ruby code tends to be single line anyway ;-)

Tags:

Ruby

Debugging