Home > Software engineering >  How do I call the supercalss's function in Ruby
How do I call the supercalss's function in Ruby

Time:06-21

I just started to learn Ruby. I have a question about how to refer to the superclass's method in the subclass if there is a method in the subclass that has the same name. In class B's method3(), I want to call method1 in class A,and not the local method. Is there a way I can call the method1 in class A instead of the method 1 in class B?

enter image description here

CodePudding user response:

I think the answer is no, you can't do it. You are doing an overriding on the method, so you give to the parent's method a new implementation. Here you can find some examples for Ruby.

So if you want to have two methods with a complete different implementation available for both Class (Parent and Child), you should use different names.

CodePudding user response:

If you really ever need this, there are two approaches I can think of:

1. Save the original method

You can create an alias (or alias_method) before overriding method1 and then call that alias just like a regular method:

class B < A
  alias orig_method1 method1

  def method1
    300
  end

  def method2
    400
  end

  def method3
    orig_method1
  end
end
2. Dynamically retrieve the super method

You can call Ruby's method to get a method object for your method and then call its super_method:

class B < A
  def method1
    300
  end

  def method2
    400
  end

  def method3
    method(:method1).super_method.call
  end
end

Both of the above will result in:

B.new.method3
#=> 400

This is because B#method3 calls A#method1 which in turn calls the receiver's method2. (which is B#method2 for instances of B)

  • Related