3

现在我的代码是这样工作的:

def method_a
  self.method_b ==> 'method_b'
end

def method_b
  puts self.name_of_calling_method
end

def name_of_calling_method
  if  /`(.*)'/.match(caller.first)
    return $1
  else
    return nil
  end
end

我怎样才能打印调用方法的名称 - 'method_a',而不是 method_b 打印'method_b'?

4

2 回答 2

3

当您从那时起被name_of_calling_method调用时,调用堆栈的上方是 1 个条目,因此您想要in而不是or 。method_bmethod_acaller[1]name_of_calling_methodcaller.firstcaller[0]

因为您已将正则表达式放在左侧,将索引放入caller右侧,所以您不需要额外检查直接调用nil的情况和是- 您的不匹配情况将涵盖它。method_bcaller[1]nil else

于 2010-04-07T20:00:14.987 回答
2

替换caller.firstcaller[1]

于 2010-04-07T18:44:55.397 回答