开发者

How to return string name of calling method?

Right now my code works as such:

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

Instead of method_b printing 'method_b', how can I print the n开发者_StackOverflowame of the calling method - 'method_a'?


When you are in name_of_calling_method called from method_b then method_a is 1 entry higher up the call stack so you want caller[1] in name_of_calling_method rather than caller.first or caller[0].

Because you've put the regexp on the left hand side and the the index into caller on the right you won't need an additional nil check for the case where method_b is called directly and caller[1] is nil - your no match else case will cover it.


Replace caller.first with caller[1].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜