Beyond puts: live state inspection

Free preview 2 min to read

The puts loop

A typical first debugging move: sprinkle puts calls through a method and rerun the whole program. You read what printed, decide it wasn't enough, add more puts calls, and rerun again.

def total_price(items)
  subtotal = items.sum
  puts "subtotal: #{subtotal}"
  subtotal * 1.1
end

That line answers one question, decided in advance: "what is subtotal". When a different question comes up mid-investigation ("wait, what's inside items?"), the file needs another puts, and the program has to run again from the top.

A different kind of tool

What if execution could pause at that line instead, so you could ask any question interactively against the live values already there? That's binding.irb, dropped straight into a method:

From: .../total_price.rb @ line 5 :

    3: def total_price(items)
    4:   subtotal = items.sum
 => 5:   binding.irb
    6:   subtotal * 1.1
    7: end

subtotal
60

No puts was written for subtotal in that file. It was asked for after the fact, at the paused prompt. It's like typing at bin/rails console, except this prompt starts inside a running method.

Why this matters, concretely

puts-debugging asks you to predict every useful piece of state before running the program even once. binding.irb removes that requirement. Once paused, you can type any expression valid at that point in the code, including ones that only occur to you after the first answer. Lesson 2 covers what binding.irb is and where it comes from.

Key takeaways

  • puts-debugging requires deciding every question in advance, then rerunning the whole program for each new one.
  • binding.irb pauses execution at that line and opens a live prompt with the real state available.
  • At that prompt, subtotal answers immediately, with nothing printed for it ahead of time.
  • The rest of this course covers what binding.irb is, what's available at that prompt, and how to resume execution afterward.
Lesson 1 of 7 · free

Keep going with lesson 2

What binding.irb actually is

Explains that binding captures the local scope and Binding#irb opens a nested IRB session, with no Rails needed.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...