Does Ruby 1.8 have an equivalent to 1.9's __callee__?
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?
精彩评论