napsterdsilva
napsterdsilva

Reputation: 173

Ruby : How to call Derived Class Method in Base Class

I want to Access the methods of the Derived class in the parent class. Please advice

Class A

 def methodA
 end

 def methodB
 end

end

Class B < Class A

 def methodC
 end

 def methodD
 end

end

I want to call methodD inside methodB

Class A
 def methodA
 end

 def methodB


 methodD
 end

end

Thanks.

Upvotes: 0

Views: 1444

Answers (3)

Rafa Paez
Rafa Paez

Reputation: 4860

Take a look at the Template Method design pattern.

Class A
 def methodA
 end

 def methodB
 end

 def methodD
  raise NotImplementedError, 'Sorry, you have to override it!'
 end
end

Class B < Class A
 def methodC
 end

 def methodD
  puts "methodD"
 end
end

In this scenario, the methodD is called a Hook Method because basically inform all concrete classes that the method may require an override. The idea is: if the base implementation is undefined the subclasses must define the hook methods.

Upvotes: 0

Matt
Matt

Reputation: 20796

What you wrote works, with some cleanups to the syntax. As long as your object is of the derived class B, then it knows what methodD is. In contrast, an object of class A will throw a NameError if you call methodB on it, since it doesn't know what methodD is.

class A

 def methodA
 end

 def methodB
   puts 'Called A#methodB'
   methodD
 end

end

class B < A

 def methodC
 end

 def methodD
   puts 'Called B#methodD'
 end

end

b = B.new
b.methodB
# Called A#methodB
# Called B#methodD

Upvotes: 3

Matheus Moreira
Matheus Moreira

Reputation: 17030

Just call the method.

class A
  def a
    b
  end
end

class B < A
  def b
    :b
  end
end

B.new.a
# => :b

Calling a method sends a message to the receiver, in this case the :b message. If the object responds to the message, then everything will just work.

You could also do this:

a = A.new

def a.b
  :x
end

a.b
# => :x

Upvotes: 0

Related Questions