4

Perl 有一个名为 Carp 的模块,可以使用它打印出消息(显式引发异常),打印消息和完整的堆栈跟踪。IE

use Carp qw(cluck) ;
cluck ("foo")

会产生:

foo called from file bar, line 2

任何想法如何在 Ruby 中获得类似的东西?

4

1 回答 1

4

你可以使用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

于 2013-11-08T11:54:38.797 回答