Skip to Content
The Ruby Programming Language
book

The Ruby Programming Language

by David Flanagan, Yukihiro Matsumoto
January 2008
Beginner to intermediate
446 pages
14h 45m
English
O'Reilly Media, Inc.
Content preview from The Ruby Programming Language

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Metaprogramming Ruby 2

Metaprogramming Ruby 2

Paolo Perrotta

Publisher Resources

ISBN: 9780596516178Supplemental ContentErrata Page