Joe Zack
Joe Zack

Reputation: 3308

How to Dynamically Determine a Method Name in Ruby

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"

Upvotes: 3

Views: 504

Answers (1)

John Feminella
John Feminella

Reputation: 311436

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.

Upvotes: 4

Related Questions