开发者

Does Ruby 1.8 have an equivalent to 1.9's __callee__?

开发者 https://www.devze.com 2023-02-13 03:09 出处:网络
I need to grab the name of the lexically enclosing method in Ruby 1.8; e.g. def foo this_method = __callee__# => \'foo\'

I need to grab the name of the lexically enclosing method in Ruby 1.8; e.g.

def foo
  this_method = __callee__  # => 'foo'
end

The above code is valid in Ruby 1.9, but fails in 1.8, since __callee__ was introduced in 1.9.

Any suggestions for doing this in 1.8? Kernel#caller looked promising, but seems to give me the call stack starting with the caller of the method, not the method itself.

I guess I could throw an exception, catch it, and grab the first element in the Exc开发者_StackOverflow社区eption#backtrace array, but my gut tells me that will be slow.


On Ruby 1.8.7 there is the __method__, not sure about 1.8.6.

Anyway, You can monkey patch the Kernel module:

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


Have you checked whether the "backports" gem has it?

0

精彩评论

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

关注公众号