O'Reilly logo

The Ruby Programming Language by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required