March 15, 2006

Where am I?

Need to get the name of the current method in Ruby?


module Kernel
def current_method
caller[0].sub(/.*`([^']+)'/, '\1').to_sym
end
end



irb(main):006:0> def test
irb(main):007:1> p current_method
irb(main):008:1> end
=> nil
irb(main):009:0> test
:test
=> nil
irb(main):010:0>


If you want to get fancier, you can get get a reference to the method itself:


module Kernel
def current_method
method(caller[0].sub(/.*`([^']+)'/, '\1').to_sym)
end
end

Labels: