Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - How can I get a method name within itself? [duplicate]

I'm trying to get a method name from itself:

def funky_method
  self.inspect
end

It returns "main".

How can I return "funky_method" instead?

like image 773
Chim Kan Avatar asked Oct 17 '12 18:10

Chim Kan


3 Answers

Here is the code:

For versions >= 1.9:

def funky_method

    return __callee__

end

For versions < 1.9:

def funky_method

    return __method__

end
like image 166
RAM Avatar answered Nov 07 '22 19:11

RAM


__callee__ returns the "called name" of the current method whereas __method__ returns the "name at the definition" of the current method.

As a consequence, __method__ doesn't return the expected result when used with alias_method.

class Foo
  def foo
     puts "__method__: #{__method__.to_s}   __callee__:#{__callee__.to_s} "
  end

  alias_method :baz, :foo
end

Foo.new.foo  # __method__: foo   __callee__:foo
Foo.new.baz  # __method__: foo   __callee__:baz
like image 30
Chetan Patil Avatar answered Nov 07 '22 21:11

Chetan Patil


Very simple:


def foo
  puts __method__
end

like image 43
Roman Avatar answered Nov 07 '22 21:11

Roman