Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Ruby method know it's name?

Tags:

ruby

Is there any way to know the name of the method currently run in Ruby?

EDIT

For example I can use self to get the current class. Is there a way to get the current method that is running? Is there a 'magic method' that can do the following?

def method1
    p "this method's name is " + magicmethod # => this method's name is method1
end
like image 206
yonso Avatar asked Dec 01 '25 08:12

yonso


2 Answers

There is __method__:

class Test
  def testing
    __method__
  end
end

Note that __method__ is a Symbol and not a String

This requires at least Ruby 1.8.7.

like image 139
ckruse Avatar answered Dec 02 '25 21:12

ckruse


How the below: :)

p RUBY_VERSION

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

class Foo
  def test_method
    method_name
  end
end

puts Foo.new.test_method 

Output:

"1.9.3"
test_method
like image 38
Arup Rakshit Avatar answered Dec 02 '25 22:12

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!