Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: is there a keyword to call a method from within itself (analogous to super)?

Tags:

ruby

keyword

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.

like image 506
Alexey Avatar asked Jan 24 '12 14:01

Alexey


People also ask

What is a method in Ruby?

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.

Which Ruby object method controls how an object is displayed in the console?

irb - Method called on an object when displayed on the console in Ruby - Stack Overflow.


1 Answers

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.

like image 123
KL-7 Avatar answered Oct 15 '22 13:10

KL-7