Debugging

p and pp

p prints the inspect form and returns the value, so you can wrap any expression without breaking the code around it.

pp pretty prints nested arrays and hashes across lines. Require the pp library first, while p needs no require. The difference between friendly and programmer output is covered in Duck typing and core idioms.

require "pp" user = { name: "Ada", age: 36 } p user pp user

Warn to stderr

warn prints to the error stream instead of normal output. Warnings stay visible even when normal output goes to a file.

Use it for deprecation notes and retries, and keep puts for real program output.

warn "Retrying in 5 seconds" puts "Continuing"

The debug gem basics

The debug gem adds breakpoints and stepping to plain Ruby. Require it, place binding dot break where you want to pause, and run the script normally.

At the prompt, type n for next line, c to continue, and p plus a name to inspect a variable.

require "debug" total = [1, 2, 3].sum binding.break puts total

Install the gem once

gem install debug

1 gem installed

Save the file as dbg.rb and run it

ruby dbg.rb

[1, 5] in dbg.rb 1| require "debug" 2| 3| total = [1, 2, 3].sum => 4| binding.break 5| puts total =>#0 <main> at dbg.rb:4 (rdbg) p total => 6 (rdbg) continue 6

The arrow marks the line that is about to run. p total prints the value right there, continue lets the program finish, and the last line is the output of puts.

Halve the code

When the bug hides in a large file, disable half the code and rerun. If the bug stays, it lives in the active half.

Repeat until the guilty lines remain. Wrapping suspects in if false is a quick switch for this game.

if false puts "suspect code here" end

Next: Exception classes and custom errors

Article author: Arthur Isaev