I am wondering: is there a way to call a method from within itself in Ruby without using its name?
If the method was created by some metaprogramming techniques, then calling it by its name may be hard to read. Even for a usually defined method, if you are not sure about a good name for it, or if its name is long, calling it from within itself by some keyword (analogous to super) may be convenient.
You can use
Kernel#__method__that returns the name of the current method as aSymbol. Unlikesuperit’s not a keyword but a regular method so you have to pass it tosendmethod along with required arguments in order to call the method.Here is what
__method__returns:And here is an example of class method that dynamically defines factorial methods:
Without
__method__I can’t think of any solution that wouldn’t involve some kind ofevalthat is better to avoid if possible.