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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With