Ruby 1.8是否相当于1.9的__callee__?

Jos*_*ver 2 ruby introspection

我需要在Ruby 1.8中获取词法封闭方法的名称; 例如

def foo
  this_method = __callee__  # => 'foo'
end
Run Code Online (Sandbox Code Playgroud)

上面的代码在Ruby 1.9中有效,但在1.8中失败,因为1.9中引入了__callee__.

有没有在1.8中做到这一点的建议?内核#caller看起来很有前途,但似乎给了我调用堆栈,从方法的调用者开始,而不是方法本身.

我想我可以抛出一个异常,抓住它,并抓住Exception #backtrace数组中的第一个元素,但我的直觉告诉我将会很慢.

khe*_*lll 5

在Ruby 1.8.7上有__method__,不确定1.8.6.

无论如何,你可以修补Kernel模块:

module Kernel
  # Defined in ruby 1.9
  unless defined?(__callee__)
    def __callee__
      caller[0] =~ /`([^']*)'/ and $1
    end
  end
end
Run Code Online (Sandbox Code Playgroud)