0

I would like to be able to identify what the name of the method is from the method which is currently being called. I have tried the following:

#!/usr/bin/env ruby
class SomeClass
  def initialize
    puts self.name
  end
end
p = SomeClass.new

but receive the following error:

./test.rb:4:in `initialize': undefined method `name' <SomeClass:0x007fe4d107ba30 (NoMethodError)
  from ./test.rb:7:in `new'
  from ./test.rb:7:in `<main>'

How do I call the method I am calling from?

rudolph9
  • 8,021
  • 9
  • 50
  • 80

2 Answers2

4
class SomeClass
  def initialize
    puts __callee__
  end
end
p = SomeClass.new #=> initialize

__method__ and __callee__ are synonyms

megas
  • 21,401
  • 12
  • 79
  • 130
  • Here are the docs for [`__callee__`/`__method__`](http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-__callee__) for reference. (Edit: SO messes up the URL, so here it is plain: `http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-__callee__` – Andrew Marshall Mar 18 '12 at 02:52
2

In Ruby methods are not regular objects that programmer can operate on them like they can do on Strings and Arrays. Thus, although Method class has name() method, when you call name() method it is searched in SomeClass and its ancestors which are [Object, Kernel, BasicObject]

You can see this by checking self in any method definition in SomeClass. It will return SomeClass as self.

Therefore, you get undefined method exception. You can use __method__ to get current method name.

class SomeClass
  def initialize
    puts __method__
  end
end

__method__ returns symbol. You can use to_s method to get the string representation of method.

emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81