新手问题 还有高手给详细的解释下 caller [1..-1] 啊

p0p3 · June 28, 2013 · Last by p0p3 replied at July 01, 2013 · 2873 hits

就是 caller(range)具体返回什么

你用 pry 设置一个断点看看内容是什么呗

调用堆栈。不是有 api 么

我不是高手啊,就是初学者,刚知道有这么个 API,翻了下文档:

Returns the current execution stack---an array containing strings in the form "file:line" or "file:line: in `method'". The optional start parameter determines the number of initial stack entries to omit from the result.

Returns nil if start is greater than the size of current execution stack.

我的理解是这样的...

比如说现在有个 test.rb 文件,里面是三个嵌套调用的 method 和几个最外层 method 调用 (照抄文档)

def a(skip)              # line 1
  caller(skip)           # line 2
end                      # line 3
def b(skip)              # line 4
  a(skip)                # line 5
end                      # line 6
def c(skip)              # line 7
  b(skip)                # line 8
end                      # line 9
c(0)   # line 10 => ["test.rb:2:in `a'", "test.rb:5:in `b'", "test.rb:8:in `c'", "test.rb:10:in `<main>'"]
c(1)   # line 11 => ["test.rb:5:in `b'", "test.rb:8:in `c'", "test.rb:11:in `<main>'"]
c(2)   # line 12 => ["test.rb:8:in `c'", "test.rb:12:in `<main>'"]
c(3)   # line 13 => ["test.rb:13:in `<main>'"]
c(4)   # line 14 => []
c(5)   # line 15 => nil

第 10 行运行时,代码执行次序是 line 10 -> line 8 -> line 5 -> line 2,在 line 2 遇到了 caller method,于是就把这个执行 stack 给放在一个数组里面 return 出来了,数组排序是执行次序反过来。

第 11 行运行时,代码执行次序是 line 11 -> line 8 -> line 5 -> line 2,在 line 2 遇到了 caller method,于是又把这个执行 stack 给 return 出来,但是 11 行传进去的参数是 1,所以第一个元素 (应该是 "test.rb:2:ina'"` 就被忽略掉了。

以下类推...

回到楼主的问题,如果在 test.rb 的最后添加一句

......
c(1..-1)  # line 16

会 return 什么呢?

推测:第 16 行运行时,代码执行顺序是 line 16 -> line 8 -> line 5 -> line 2,在 line 2 遇到 caller method , 此时把 stack 放进数组 return 出来。完整的数组应该是:

["test.rb:2:in `a'", "test.rb:5:in `b'", "test.rb:8:in `c'", "test.rb:16:in `<main>'"]

但是传入了一个 range : 1..-1 ,这个 range 其实就是去掉数组的第一个元素 (index 0)

所以推测最后结果应该是:

["test.rb:5:in `b'", "test.rb:8:in `c'", "test.rb:16:in `<main>'"]

经测试正确...

呵呵,我说的是 caller[1..-1],不是你说的 caller(1..-1),不是你说的这个意思,不过谢谢你啊,我弄清楚了

caller 返回的是 array,所以接着 [1..-1] 仅仅是对数组的操作而已

呵呵,是的,就是 ls 说的意思,谢谢啊

You need to Sign in before reply, if you don't have an account, please Sign up first.