Inside one method I am writing, how can my code know which method it is currently in? I need this because I want to get the method name and parse it to get a part of it, such as "add_order", then I can use the second part "order" to work on.
Asked
Active
Viewed 147 times
0
-
2Duplicate: http://stackoverflow.com/questions/199527/get-the-name-of-the-currently-executing-method-in-ruby http://stackoverflow.com/questions/5100299/how-to-get-the-name-of-the-calling-method http://stackoverflow.com/questions/10467625/how-to-retrieve-the-current-method-name-so-to-output-it-to-the-logger-file – halfelf Feb 25 '13 at 07:52
-
see this: http://stackoverflow.com/questions/199527/get-the-name-of-the-currently-executing-method-in-ruby – kikuchiyo Feb 25 '13 at 07:54
-
@halfelf that one is for getting the caller method name and not the one you are currently in – Zaid Amir Feb 25 '13 at 07:55
-
@RedSerpent try `caller(0)` – Aleksei Matiushkin Feb 25 '13 at 08:35
2 Answers
5
use __method__
to get the name of the method you are currently in

Zaid Amir
- 4,727
- 6
- 52
- 101
-
You are right. I just found it! http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-__method__ – Juguang Feb 25 '13 at 08:08
0
def get_mname
caller[0]=~/`(.*?)'/ # quote is a backtick
$1
end
def name_of_my_method
puts get_mname
end
name_of_my_method
# => name_of_my_method

peter
- 41,770
- 5
- 64
- 108