Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a super class method

Tags:

ruby

I have two classes A, and B. Class B overrides the foo method of class A. Class B has a bar method where I want to call the foo method of the super class. What is the syntax for such a call?

class A      def foo    "hello"  end     end   class B < A  def foo   super + " world"  end   def bar    # how to call the `foo` method of the super class?    # something similar to    super.foo  end end 

For class methods I can call the methods up the inheritance chain by explicitly prefixing the class name. I wonder if there is a similar idiom for instance methods.

class P  def self.x    "x"  end end  class Q < P  def self.x    super + " x"  end   def self.y    P.x  end end 

Edit My use case is general. For a specific case I know I can use alias technique. This is a common feature in Java or C++, so I am curious to know if it is possible to do this without adding extra code.

like image 596
Harish Shetty Avatar asked Apr 02 '10 00:04

Harish Shetty


People also ask

Can we call super in method?

2) super can be used to invoke parent class method The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.

Can we call super super method in Java?

The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.

When super () is called?

super() is implicit when no other class/superclass constructor is called.

How do you call a super method in Python?

super() returns a delegate object to a parent class, so you call the method you want directly on it: super(). area() .


1 Answers

In Ruby 2.2, you can use Method#super_method now

For example:

class B < A   def foo     super + " world"   end    def bar     method(:foo).super_method.call   end end 

Ref: https://bugs.ruby-lang.org/issues/9781#change-48164 and https://www.ruby-forum.com/topic/5356938

like image 85
zlx_star Avatar answered Sep 30 '22 07:09

zlx_star