Perl有一个名为Carp的模块,可以用来打印消息(w.o explcitly引发异常),打印消息和完整的堆栈跟踪。 即。
use Carp qw(cluck) ;
cluck ("foo")
会屈服:
foo called from file bar, line 2
如何在Ruby中获得类似的东西?
答案 0 :(得分:3)
您可以Kernel#caller_locations
使用此http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-caller_locations)
def cluck(val)
loc = caller_locations.last
puts "#{val} called from file #{loc.path}, line #{loc.lineno}"
end
cluck 1
cluck "hello"
输出:
1 called from file line_of_caller.rb, line 6
hello called from file line_of_caller.rb, line 7
loc
这里是Thread :: Backtrace :: Location的一个实例,所以你也可以从中获取更多信息;看看http://www.ruby-doc.org/core-2.0.0/Thread/Backtrace/Location.html