Inline Diagnostics

Although some consider it a haphazard and undisciplined practice, inserting a few STDERR.print statements at strategic places is often enough to clue you in to what is going wrong with an errant script. When method bodies are relatively small (as they generally should be), a stack trace can help you see where those strategic places are.

Upon examination of the stack trace in the previous section, it seems likely that a diagnostic message in the times iterator block, such as the following, would be helpful:

n.times do |i|
  STDERR.puts "i == #{i} "
  sum += quux(i)
end

Now, when you run the script, the following extra output discloses the value of i being fed to quux:

~/testcode:>ruby div0.rb i == 0 i == 1 i == 2 i == 3 i == ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.