A Method That Knows Its Own Name: this_method()
By chris on January 14th 2008 in /dev/ruby | 432 views
I realize this is the second mailing list-mining for content this week but this was too cool to not mention. Over in Ruby Forum in using the current method name within current method Aleks Kissinger, Robert Klemme, and Matt Todd hashed out a way for methods in Ruby 1.8 to know their own identity.
To jump to the end, the final solution is:
module Kernel
private
def this_method
caller[0] =~ /`([^']*)’/ and $1
end
end
As an example:
class TestClass
def this_methods_name
puts this_method
end
end
t = TestClass.new
t.this_methods_name
Pretty cool stuff, that.