简体   繁体   English

Ruby:如何在基类中调用派生类方法

[英]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我想在methodB里面调用methodD

Class A
 def methodA
 end

 def methodB


 methodD
 end

end

Thanks.谢谢。

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.只要您的对象属于派生类B ,那么它就知道methodD是什么。 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.相比之下,类A的对象在调用methodB时会抛出NameError ,因为它不知道methodD是什么。

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

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.调用一个方法会向接收者发送一条消息,在这种情况下是:b消息。 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

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.在这种情况下, methodD被称为Hook Method因为基本上通知所有具体类该方法可能需要覆盖。 The idea is: if the base implementation is undefined the subclasses must define the hook methods.这个想法是:如果基本实现未定义,则子类必须定义钩子方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM