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.
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.
Wherever you would put a puts statement, replace with ‘debugger; true’.
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
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?
 ‘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.
Interested in learning more about our basic and advanced Back-End Courses?
Learn from the experts at a Big Nerd Ranch Bootcamp!
Interested in leveling up your coding skills from the same authors of the Big Nerd Ranch Guide? Subscribe to The Frontier today!
Chris Downie and Sam Landfried