Ruby--Kernel#caller方法

来源:互联网 发布:数据库事务日志已满 编辑:程序博客网 时间:2024/06/06 09:56

用途:
caller可以返回当前位置的调用者详细信息,异常的错误栈信息(Exception#backtrace)即通过该方法获得。

caller([level])

以$@的back trace(字符串数组)形式返回level层上(省略参数时为1)的调用者的信息。若是顶层的话就返回空数组。将caller的返回值代入$@就可以设定异常的发生位置。

示例:
def foo
p caller(0)
p caller(1)
p caller(2)
p caller(3)
end

def bar
foo
end

bar

=> [“-:2:in foo'", "-:9:inbar’”, “-:12”]
[“-:9:in `bar’”, “-:12”]
[“-:12”]
[]

参考资料:
http://ruby-doc.org/core-2.3.0/Kernel.html#method-i-caller
http://www.kuqin.com/rubycndocument/man/stdlib_function.html

0 0
原创粉丝点击