views:

188

answers:

2

In Ruby, is there a way to determine the name of a method, akin to how the "class" method returns an object's type?

For example:

def example_method
  puts method_name
end

#=> "example_method"
+3  A: 

Try this method, from here:

module Kernel
 private
  def current_method_name
    caller[0] =~ /`([^']*)'/ and $1
  end
end


class Foo
 def test_method
   current_method_name   # "test_method"
 end
end

This works in older versions of Ruby (< 1.9). For newer versions, see the other StackOverflow answer here highlighted by Ben.

John Feminella