先贴上一段代码:
运行的结果为:
"This is func1"
"E:/test/exptest.rb:8:in `func2'"
"This is func2"
"E:/test/exptest.rb:14:in `func3'"
"This is func3"
"E:/test/exptest.rb:21"
若修改代码如下:
则得到运行结果如下显示:
"This is func1"
"E:/test/exptest.rb:21"
"This is func2"
"E:/test/exptest.rb:21"
"This is func3"
"E:/test/exptest.rb:21"
从上述两者的比较中,可以看出:
caller[i]得到调用者函数,由于调用者存放于栈上,因此,i分级为0、1、2......
caller[0]显示第0级调用者,caller[1]显示第1级调用者...caller[i]显示第i级调用者。
caller[i]在Ruby中很有用的地方是能够用来进行调试,清楚地显示本地函数的调用者。
特别是写MK2/3的时候,这一点非常有用。