While we're having fun reflecting on all the objects and classes in
our programs, let's not forget about the humble statements that make
our code actually do things. It turns out that Ruby lets us look at
these statements, too.
First, you can watch the interpreter as it executes code.
set_trace_func
executes a
Proc
with all sorts of juicy
debugging information whenever a new source line is executed,
methods are called, objects are created, and so on. There's a full description
on page 422, but here's a taste.
class Test
def test
a = 1
b = 2
end
end
set_trace_func proc { |event, file, line, id, binding, classname|
printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}
t = Test.new
t.test
|
produces:
line prog.rb:11 false
c-call prog.rb:11 new Class
c-call prog.rb:11 initialize Object
c-return prog.rb:11 initialize Object
c-return prog.rb:11 new Class
line prog.rb:12 false
call prog.rb:2 test Test
line prog.rb:3 test Test
line prog.rb:4 test Test
return prog.rb:4 test Test
|
There's also a method
trace_var
(described
on page 427) that lets you add a hook to a global variable; whenever
an assignment is made to the global, your
Proc
object is invoked.