MxLDevs
MxLDevs

Reputation: 19506

Calling a parent's method from the child

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

Answers (1)

Koraktor
Koraktor

Reputation: 42923

Parent.instance_method(:print).bind(self).call

This is already pretty readable, but here's an explanation.

  1. Get the #print method of the Parent class
  2. Bind it to your current object
  3. Call it

PS: 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

Related Questions