3

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"
Joe Zack
  • 3,268
  • 2
  • 31
  • 37

1 Answers1

4

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.

Community
  • 1
  • 1
John Feminella
  • 303,634
  • 46
  • 339
  • 357