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.
A method in Ruby is a set of expressions that returns a value. Within a method, you can organize your code into subroutines which can be easily invoked from other areas of their program. A method name must start a letter or a character with the eight-bit set.
irb - Method called on an object when displayed on the console in Ruby - Stack Overflow.
You can use Kernel#__method__
that returns the name of the current method as a Symbol
. Unlike super
it's not a keyword but a regular method so you have to pass it to send
method along with required arguments in order to call the method.
Here is what __method__
returns:
obj = Object.new
def obj.foo
p __method__
end
obj.foo
# => :foo
And here is an example of class method that dynamically defines factorial methods:
class Foo
def self.define_fact(method_name)
define_method(method_name) do |n|
n > 0 ? n * send(__method__, n - 1) : 1
end
end
end
f = Foo.new
# puts f.fact(5)
# => undefined method `fact' for #<Foo:0x8ede45c> (NoMethodError)
Foo.define_fact :fact
puts f.fact(5)
# => 120
Without __method__
I can't think of any solution that wouldn't involve some kind of eval
that is better to avoid if possible.
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