How to Read Code | 51def bar
pp caller
'baz'
end
endputs Test.new.fooThis gives us the call stack:
["./call_stack1.8.4.rb:8:in `foo'", "./call_stack1.8.4.rb:17"]
bazHowever, this method is clunky. There is very little information that we can use pro-
grammatically; this is mainly for informational use. A more flexible stack trace mecha-
nism comes from Mauricio Fernández’s call_stack library,*which hooks entry and exit
of every method, providing that information at the request of the globalcall_stack
method. This library was developed because Ruby 1.8.5 broke the old implementation
ofBinding.of_caller(which relied on a bug in 1.8.4). However,call_stackworks on
1.8.4 as well. We get much more information throughcall_stack:
#!/usr/local/bin/rubyrequire 'rubygems'
require 'call_stack'
require 'pp'class Test
def foo
bar
enddef bar
pp call_stack(-1)
"baz"
end
endcall_stack_onputs Test.new.foocall_stack_offThecall_stack_onandcall_stack_offfunctions add and remove the hook func-
tions that keep track of function execution, so you must callcall_stack_onbefore
starting to capture frames. Thecall_stackfunction yields an array of stack frames;
each frame is an array containing [class_name,method_name,filename,line,binding,
language]. This code prints: