Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method in parent class from subclass methods in Ruby

Tags:

ruby

I've used super to initialize parent class but I cannot see any way of calling parent class from subclass methods.

I know PHP and other languages do have this feature but cannot find a good way to do this in Ruby.

What would one do in this situation?

like image 259
Passionate Engineer Avatar asked Aug 26 '13 16:08

Passionate Engineer


People also ask

Can a superclass call the methods of a subclass?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

Can you call a parent class method from child class object?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.


1 Answers

If the method is the same name, i.e. you're overriding a method you can simply use super. Otherwise you can use an alias_method or a binding.

class Parent   def method   end end  class Child < Parent   alias_method :parent_method, :method   def method     super   end    def other_method     parent_method     #OR     Parent.instance_method(:method).bind(self).call   end end 
like image 113
Mark Meyer Avatar answered Nov 08 '22 02:11

Mark Meyer