Check out our Bootcamp Schedule View Schedule

Debugging Best Practices

Jonathan Wallace

At rubyhoedown, the inimitable Jim Weirich gave an awesome presentation on using the debugger in ruby. Before his new found respect for the ruby debugger, Jim told us that puts statements worked just fine for him.

And this is true. You can get by with puts. But, you can get by much faster using the debugger. Read on to find out when to use the debugger and how.

Firstly, when should you use the the ruby debugger? Simple.

Actually, there is one case in which puts is better than the debugger but let’s touch on that later. For now, let us look at how to use the debugger.

  1. Require ruby-debug in your source code. Use ruby-debug19 for ruby 1.9+. If in rails, add ruby-debug / ruby-debug19 to your Gemfile.

  2. Wherever you would put a puts statement, replace with ‘debugger; true’.[0]

Once you’re in the debugger, you can revert to your puts using ways. puts any expression to evaluate it. Protip: or type in ‘set autoeval’ so you don’t have to use puts!! You can even set this in an .rdebugrc file. Example

The sweet spot of debugger commands.

  1. n – step over the next line (don’t step into a function)
  2. s – step into the next line (into a function or block)
  3. c – continue until another breakpoint or execution completes
  4. v l – view all locally scoped variables

For a more comprehensive overview of commands, check out errtheblog’s cheatsheet.

Now, as I mentioned before, there is one time where I like puts over the ruby debugger. When you want to view the change of data throughout the execution of a program, puts to a log file will give you a higher level overview.

Can you think of any others? How do you use the debugger?

[0] ‘debugger’ does not act like a traditional breakpoint. Instead of halting execution before the ‘debugger’ line, the ruby-debugger halts execution after. Therefore, we drop a ‘; true’ to ensure that we don’t step out of a function or into a method.

Not Happy with Your Current App, or Digital Product?

Submit your event

Let's Discuss Your Project

Let's Discuss Your Project