Tracing

Ruby defines a number of features for tracing the execution of a program. These are mainly useful for debugging code and printing informative error messages. Two of the simplest features are actual language keywords: __FILE__ and __LINE__. These keyword expressions always evaluate to the name of the file and the line number within that file on which they appear, and they allow an error message to specify the exact location at which it was generated:

STDERR.puts "#{__FILE__}:#{__LINE__): invalid data"

As an aside, note that the methods Kernel.eval, Object.instance_eval, and Module.class_eval all accept a filename (or other string) and a line number as their final two arguments. If you are evaluating code that you have extracted from a file of some sort, you can use these arguments to specify the values of __FILE__ and __LINE__ for the evaluation.

You have undoubtedly noticed that when an exception is raised and not handled, the error message printed to the console contains filename and line number information. This information is based on __FILE__ and __LINE__, of course. Every Exception object has a backtrace associated with it that shows exactly where it was raised, where the method that raised the exception was invoked, where that method was invoked, and so on. The Exception.backtrace method returns an array of strings containing this information. The first element of this array is the location at which the exception occurred, and each subsequent element is one stack frame ...

Get The Ruby Programming Language 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.