Get the name of the currently executing method

RubyReflectionMetaprogramming

Ruby Problem Overview


$0 is the variable for the top level Ruby program, but is there one for the current method?

Ruby Solutions


Solution 1 - Ruby

Even better than my first answer you can use __method__:

class Foo
  def test_method
    __method__
  end
end

This returns a symbol – for example, :test_method. To return the method name as a string, call __method__.to_s instead.

Note: This requires Ruby 1.8.7.

Solution 2 - Ruby

Depending on what you actually want, you can use either __method__ or __callee__, which return the currently executing method's name as a symbol.

On ruby 1.9, both of them behave identically (as far as the docs and my testing are concerned).

On ruby 2.1 & 2.2 __callee__ behaves differently if you call an alias of the defined method. The docs for the two are different:

  • __method__: "the name at the definition of the current method" (i.e. the name as it was defined)
  • __callee__: "the called name of the current method" (i.e. the name as it was called (invoked))

Test script:

require 'pp'
puts RUBY_VERSION
class Foo
  def orig
    {callee: __callee__, method: __method__}
  end
  alias_method :myalias, :orig
end
pp( {call_orig: Foo.new.orig, call_alias: Foo.new.myalias} )

1.9.3 Output:

1.9.3
{:call_orig=>{:callee=>:orig, :method=>:orig},
 :call_alias=>{:callee=>:orig, :method=>:orig}}

2.1.2 Output (__callee__ returns the aliased name, but __method__ returns the name at the point the method was defined):

2.1.2
{:call_orig=>{:callee=>:orig, :method=>:orig},
 :call_alias=>{:callee=>:myalias, :method=>:orig}}

Solution 3 - Ruby

From http://snippets.dzone.com/posts/show/2785:

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

class Foo
  def test_method
    this_method_name
  end
end

puts Foo.new.test_method    # => test_method

Solution 4 - Ruby

For Ruby 1.9+ I'd recommend using __callee__

Solution 5 - Ruby

I got the same issue to retrieve method name in view file. I got the solution by

params[:action] # it will return method's name

if you want to get controller's name then

params[:controller] # it will return you controller's name

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsalt.racerView Question on Stackoverflow
Solution 1 - RubyMark A. NicolosiView Answer on Stackoverflow
Solution 2 - RubyKelvinView Answer on Stackoverflow
Solution 3 - RubyMark A. NicolosiView Answer on Stackoverflow
Solution 4 - Rubyl3xView Answer on Stackoverflow
Solution 5 - RubyHetal KhuntiView Answer on Stackoverflow