Skip to content
Tutorials Center
My learning

Topics

Lesson 104 of 134 ยท Testing and Tooling

Debugging Ruby

Learn practical Ruby debugging: read errors and backtraces, print with p and pp, trace calls with caller and TracePoint, and use binding.irb and the debug gem.

Every programmer spends a large part of their time not writing code but finding out why code does not do what they expected. Debugging is a skill with a method behind it, not a matter of luck. The method is always the same: make the problem reproducible, shrink it, form a hypothesis, test the hypothesis with a print or a debugger, and fix the cause rather than the symptom.

This lesson gives you the Ruby tools for each step: reading the messages Ruby already gives you (they are better than most people think), printing values with p and pp, finding out who called a method with caller, tracing execution with TracePoint, and stopping a running program with binding.irb and the debug gem. The interactive tools need a terminal, so they appear as read-only snippets; everything else runs here.

Step zero: read the error message

Ruby's error messages carry a lot of information, and reading them fully solves a large share of bugs before you debug anything. A message has three parts: where (file, line and method), what (the message and the class in parentheses) and how you got there (the backtrace, newest call first).

Ruby Reading a NoMethodError from top to bottom (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output is main.rb:2:in 'Object#shout': undefined method 'upcase' for nil (NoMethodError), followed by a copy of line 2 with carets under .upcase, and then two from lines: main.rb:6:in 'Object#report' and main.rb:9:in '<main>'. Reading it:

  1. Line 2, inside shout is where the exception was raised. Start there.
  2. undefined method 'upcase' for nil means we asked nil to do something. nil is the real problem, so the question becomes "why is words[key] nil?".
  3. The carets (from the error_highlight feature) point at the exact call that failed.
  4. The from lines are the callers. The mistake may be in a caller that passed bad data, here the key :missing.

The two most common messages in Ruby are undefined method 'x' for nil (something you expected to exist is nil) and wrong number of arguments (given 1, expected 2) (ArgumentError). A close third is undefined local variable or method, which usually means a typo, and Ruby even suggests the fix:

Ruby Typos and did_you_mean suggestions (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You see undefined local variable or method 'totla_price' for main (NameError) and below the code excerpt a line Did you mean? total_price. The same feature suggests method names, for example frist becomes first. Always read the suggestion before searching anywhere else.

When you catch an exception yourself, e.full_message(highlight: false) returns the same text Ruby prints for an uncaught one, with the excerpt and the backtrace. e.backtrace is just the array of from lines, and e.backtrace_locations gives objects with lineno, path and label. Log full_message, not just e.message, or you will lose the where.

Printing values: puts, p and pp

The oldest debugging tool is still the most used: print something and look. Ruby has three print methods, and choosing the right one matters.

  • puts shows the display form (to_s). nil becomes an empty line and a string shows without quotes, so you cannot tell nil, "" and "nil" apart.
  • p shows the inspect form: strings with quotes, symbols with a colon, nil as nil. It also returns its argument, so you can insert it into an expression without changing the program.
  • pp is p with line breaks and indentation for big nested structures.
Ruby puts versus p versus pp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Three tricks are worth remembering. First, because p returns its argument, p(n * 2) inside the block prints every value without breaking the sum. Second, p(x:, y:) uses the hash shorthand to print labelled values ({x: 1, y: "two"}), so you never wonder which number belongs to which variable. Third, pp breaks a hash across lines only when it does not fit, so small values stay on one line.

Print debugging output to standard error with warn when your program's real output goes to standard output: warn "total=#{total}". The debug lines then do not mix into data you pipe to another program. warn "message", uplevel: 0 also prefixes the file and line of the call, as in main.rb:12: warning: message.

Inspecting your own objects

p calls inspect. For your own classes the default prints the class name, an address and all instance variables, such as #<User:0x000... @name="a", @tags=[1, 2]>. The address changes on every run, so for readable debugging output define inspect (see to_s, inspect and Conversions):

Ruby A custom inspect that helps you debug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

p orders now shows one compact line per order. Two guidelines for a good inspect: include the identity (an id or name) and the few fields you need most, and never raise an error inside it, because a crash while printing hides the bug you are chasing.

Who called me? caller and call stacks

Sometimes the failing method is fine and the caller is wrong, or a method is called from places you did not expect. caller returns the call stack as an array of strings, and caller_locations returns objects you can ask for the label or line number.

Ruby Printing the call stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

caller_locations(1, 1) means "skip one frame (log itself) and give me one frame": the code that called log. That is how logging libraries print the origin of a message. caller(0) includes the current frame as well, which is handy for a quick "how did I get here?" dump inside a method that runs too often. You can store caller in a variable and print it only under a condition, such as when a value first becomes nil.

Tracing execution with TracePoint

A TracePoint tells you every time a certain event happens: a method is called, returns, a line runs or an exception is raised. It is a powerful way to learn what a piece of code actually does without editing it.

Ruby Tracing calls and return values with TracePoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You see call sum_of_squares, then call square and return square => 4, call square and return square => 9, and finally return sum_of_squares => 13. That is a complete execution trace of your own methods. Use the block form of enable, as above, so the tracing stops by itself, and keep the traced region small: tracing everything is slow and noisy.

You can also trace exceptions: TracePoint.new(:raise) { |tp| puts tp.raised_exception.inspect } reports every exception raised, including ones the program rescues silently, which is a quick way to find a swallowed error.

A debugging session, step by step

Let us debug a realistic bug. This median method is supposed to return the middle value of a list, or the average of the two middle values when the list has an even length. The tests we ran in our heads said it works, but the last call is wrong.

Ruby A median that is wrong for even lists (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first call prints 3, which is right. The second prints 3, but the median of 1, 2, 3, 4 is 2.5. The method does not crash: the bug is a wrong result, and those are the hardest kind. Apply the method:

  1. Reproduce and shrink. median([4, 1, 3, 2]) fails; median([5, 1, 3]) works. Odd works, even does not. That is already a strong hint.
  2. Look at the values. Print the intermediate variables with labels.
Ruby Printing intermediate values with labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The labelled line {sorted: [1, 2, 3, 4], middle: 2} shows that sorted[2] is 3, the upper of the two middle values. For an even-sized list we need positions 1 and 2. Now the hypothesis is precise, and the fix is small:

Ruby The fixed median with checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

All four cases behave. The empty list now fails loudly with a clear message instead of returning nil and causing a confusing error somewhere else later. After fixing a bug, write a test that fails without the fix (see Testing with Minitest), so the bug cannot return unnoticed.

Stopping the program: binding.irb and the debug gem

Printing is slow when you do not know what to print. A debugger pauses the running program so you can look around and try things. Ruby offers two. These are read-only examples, because they need an interactive terminal that our runner does not have.

binding.irb opens an IRB prompt inside the running program, with access to all local variables at that point:

Ruby
# read-only: run with `ruby median.rb` in a terminal
def median(numbers)
  sorted = numbers.sort
  middle = sorted.size / 2
  binding.irb                # execution stops here and you get a prompt
  sorted[middle]
end

median([4, 1, 3, 2])

At the irb(main):001> prompt you can type sorted, middle and sorted.size.even?, call methods, and change variables. Type exit to continue. Since Ruby 3.1, IRB also has commands such as show_source, ls (list methods and variables) and edit.

The debug gem (shipped with Ruby as a bundled gem) is a full step debugger. Add debugger or binding.break to the code, or start the script with rdbg:

Terminal
# read-only: needs a terminal
ruby -r debug median.rb          # stops at the first line
rdbg median.rb                   # the same, using the debugger executable
TEXT
# the most useful debugger commands (typed at the (rdbg) prompt)
n  / next        run the next line, stepping over method calls
s  / step        step into the method call on this line
c  / continue    run until the next breakpoint
fin / finish     run until the current method returns
bt / backtrace   show the call stack
i  / info        list local variables
p expr           print the value of an expression
b 12 / break 12  set a breakpoint on line 12 of this file
b Order#total    set a breakpoint when a method is called
watch @balance   stop when an instance variable changes
q / quit         leave the debugger

The ability to set a breakpoint, continue, and inspect replaces dozens of print statements. Learn n, s, c, bt, i and p, and you can debug almost anything. Editors such as VS Code and RubyMine drive the same debug gem with a graphical interface and clickable breakpoints.

Never commit a binding.irb, debugger or stray p into your main branch. A binding.irb in a web request handler will hang the server waiting for input. A pre-commit hook or a linter rule (see Style and Linting) can catch these automatically.

Other useful tools

  • Warnings. Run scripts with ruby -w script.rb to see warnings about unused variables, ambiguous syntax and suspicious code. Fix them; each one is a possible bug.
  • tap in a chain. .tap { |x| p x } shows the value flowing through a method chain without changing it:
Ruby Peeking into a method chain with tap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

  • binding.local_variables lists the names of local variables at that point, and binding.local_variable_get(:name) reads one by name, which helps in helper methods for debugging.
  • Method#source_location and method(:name).owner tell you where a method is defined and which class provides it, which answers "which to_s is this really calling?". See Reflection and Introspection.
  • git bisect. When something used to work and now does not, git bisect finds the commit that broke it by binary search. It is a command-line tool and a very efficient bug finder.
  • Rubber-duck debugging. Explain the code line by line, out loud, to a rubber duck or a colleague. Explaining forces you to state your assumptions, and the wrong one often reveals itself.

Common mistakes

  • Fixing the symptom. Adding || 0 or &. to silence a nil error, without asking why it is nil, hides the real bug until it returns somewhere else.
  • Guessing instead of observing. Print or inspect the actual values before you decide what is wrong.
  • Changing several things at once. You then do not know which change helped. Make one change, run, observe.
  • Reading only the last line of a backtrace. The top line is where the error was raised, but the cause is often in a caller further down.
  • Debugging in the dark. If a bug does not reproduce reliably, first find the input or the timing that does reproduce it.
  • Leaving debug output behind. Remove temporary prints, or send them to warn/a logger and keep them intentional. See OptionParser and Logger.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A backtrace shows several from lines under the error line. What does the top error line tell you?

    The first line names the file, line and method where the exception was raised. The from lines below it are the callers, newest first.
  2. 2. Why is p often better than puts for debugging?

    puts shows the to_s form, so nil and an empty string look alike. p shows inspect and returns the value, so it can be inserted into an expression.
  3. 3. What does p(x:, y:) print when x is 1 and y is "two"?

    The hash shorthand builds the hash {x: x, y: y}, so each value is printed with its variable name.
  4. 4. Which call returns the code location that called the current method?

    caller_locations(1, 1) skips the current frame and returns one location object. Its label and lineno describe the caller.
  5. 5. Why should you never leave binding.irb in code that is committed?

    binding.irb opens an interactive prompt and blocks until you leave it. In a server or a scheduled job nobody is there to type exit.

Summary

  • Debug with a method: reproduce, shrink, hypothesize, observe, fix the cause, then add a test.
  • Read error messages fully: file and line, class and message, the code excerpt with carets, Did you mean? hints and the backtrace.
  • p shows the inspect form and returns its argument; p(x:, y:) labels values; pp formats nested data; warn sends debug output to standard error.
  • Define a short inspect on your own classes so printed objects are readable.
  • caller and caller_locations show who called a method; TracePoint records calls, returns and exceptions.
  • binding.irb and the debug gem (with commands such as n, s, c, bt, i) pause a running program; they need a terminal and never belong in committed code.
  • Use tap to peek into method chains and ruby -w to surface hidden problems.

Next: RubyGems and Bundler