How to use Byebug to debug Ruby code
With Ruby 2.0 (and later), use the byebug gem to debug your code:
gem install byebug
(Note version 1.X of Ruby used ruby-debug, but that library no
longer works.)
To debug a particular Ruby program add
require 'byebug'
at the top of the program and call
byebug
wherever you'd like the application to "break" - that is, executing
byebug is equivalent to putting a breakpoint in your code.
Run the program and use the debugger commands once
you reach the breakpoint.
For Rails applications, edit config/environments/development.rb
and add the line
require 'byebug'
near the end. Restart your server. You can then add byebug
statements to your Rails code. The server will enter the debugger shell
and you can use the commands.
Debugger Commands
You're supposed to be able to get a list of debugger commands by typing
help at the prompt, but this doesn't seem to be working. See
the cheetsheet
for a list of commands. The
most common commands are
- b: set a break point at a given line number
- c: run until program ends or reaches a breakpoint
- s: step forward by one instruction, stepping into function calls
- n: step to the next statement, stepping over function
calls
- v l: list local variables
- p: print the value of an expression: p methods
- pp: pretty-print the value of an expression: p methods
- eval: evaluate expression (which can be an assignment) and print
the result; for example, eval n = 10. You can also just type the
expression - the eval isn't required.
- info line: print current location
- l: list the lines of code just before and just after the current
line
- The list command actually advances forward each time, so a second usage
of l shows the next few lines. Entering "l =" shows the
current line again, and if you step or otherwise change the current line
the list command goes back to the current execution point.
- irb: starts an interactive ruby shell inside your application -
use exit (or the end-of-file key) to return to the ruby debugger
prompt.
- finish: run to the end of the current function
- q: quit
Note that most commands come in a long and short form; for instance,
list does the same as l.