Perl有一个名为carp的模块,可以用来打印消息(w.o显式地引发异常),它打印消息和完整的堆栈跟踪。
即。
use Carp qw(cluck) ;
cluck ("foo")
将屈服:
foo called from file bar, line 2
有什么办法在ruby中得到类似的东西吗?
最佳答案
您可以使用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