18

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?

cdesrosiers
  • 8,862
  • 2
  • 28
  • 33
Thanks for all the fish
  • 1,671
  • 3
  • 17
  • 31

3 Answers3

30

Here is the code:

For versions >= 1.9:

def funky_method

    return __callee__

end

For versions < 1.9:

def funky_method

    return __method__

end
RAM
  • 2,413
  • 1
  • 21
  • 33
  • 1
    Only `__method__` will work in 1.8, `__callee__` comes with 1.9 – UncleGene Oct 18 '12 at 00:40
  • 1
    So, you're saying that `__method__` doesn't work for Ruby Version >= 1.9? According to Chetan Patil's answer, they produce different values, the caller versus the method name you're in. – Joshua Pinter May 22 '15 at 16:31
15

__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
Chetan Patil
  • 179
  • 1
  • 3
2

Very simple:


def foo
  puts __method__
end

Roman
  • 13,100
  • 2
  • 47
  • 63