Reputation: 19506
Some code
class Parent
def print
p "Hi I'm the parent"
end
end
class Child < Parent
def initialize(num)
@num = num
end
def print
child_print
end
def child_print
if @num == 1
#call parent.print
else
p "I'm the child"
end
end
end
c1 = Child.new(1)
c2 = Child.new(2)
c1.print
c2.print
Child
is an instance of Parent
. Print
is the method exposed in the interface, and both classes define them. Child
decides to do other things in a (possibly really complex) method, but will invoke its parent's method under some condition.
I could just write
def print
if @num == 1
super
else
p "I'm the child"
end
end
And that works, but what if it's not just a simple one-liner comparison but instead is doing lots of complicated things that deserve to be separated into another method? It may have to do some calculations before deciding that the parent's method should be called.
Or perhaps there is a different, better way to design it.
Upvotes: 0
Views: 765
Reputation: 42923
Parent.instance_method(:print).bind(self).call
This is already pretty readable, but here's an explanation.
#print
method of the Parent
classPS: You can even give arguments to #call
and they will be relayed to the called method.
PPS: That said, such code almost always hints at an issue in your class design. You should try to avoid it whenever possible.
Upvotes: 1