Interactive debugging can sometimes be faster and more effective in helping you code than a
puts statement. It’s easy to get interactive debugging in Ruby or on Rails with the help of a nice gem.
No IDE Required
There are Ruby IDEs that provide interactive debugging capabilities. My favorite is RubyMine by Jetbrains. But if you don’t have or don’t want an IDE, there’s still hope.
Include the dependency
My new buddy George showed me a sweet gem simply named
debugger. To use it, I first add the
debugger dependency to my
1 2 3
Add a breakpoint
Next, I need to add my “breakpoint” into my code that I’m going to run. In this case, the breakpoint is defined by calling
debugger. On the same line, we’ll also import the
1 2 3 4 5
Run your code
In this example, I’m going to break right after I call the
is_anagram? method. From the terminal, now I exercise the code. In this case, I’ll run my unit tests:
Debug like a champ
And when execution of the script gets to the
debugger line, execution will pause and output in my terminal will look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A snippet of my code is shown, an arrow points at line 13, and there’s a prompt at the bottom (labeled ‘rdb’) that you can type in.
debugger gives you a few special commands to type, such as:
s- step over
These commands should be familiar to almost all debuggers. The other fabulous thing is that the prompt functions as a sort of
irb session from the current context of your code. So, I can type variable names to see their contents or call functions to see what they’d return. So, in the case of this code, I could try:
1 2 3 4
Pretty cool and pretty powerful all for the price of including the library and including a breakpoint in your code.
Are there tools similar to this that you love to use for debugging?