Ruby中的’include’和’prepend’有什么区别?
从
Module
任何人都可以帮助我了解以下问题: >除了默认值之外,Module的哪些功能被定义为附加和前缀? 解决方法
>模块的哪些特征被定义为附加和前缀?
如您所引用的文字所述:
>他们的功能差异如何? 将混合模块的方法都添加到传递的模块(类)中.区别在于这些方法的查找顺序,如果目标类已经定义了它们: include的行为就好像目标类继承了mixed-in模块: module FooBar def say puts "2 - Module" end end class Foo include FooBar def say puts "1 - Implementing Class" super end end Foo.new.say # => # 1 - Implementing Class # 2 - Module prepend使得混合模块中的方法“更强”,并先执行它们: module FooBar def say puts "2 - Module" super end end class Foo prepend FooBar def say puts "1 - Implementing Class" end end Foo.new.say # => # 2 - Module # 1 - Implementing Class 这个例子从这里撕下来:http://blog.crowdint.com/2012/11/05/3-killer-features-that-are-coming-on-ruby-2-0.html >何时使用append_features和prepend_features? 当您想要在方法查找链的末尾保留目标模块(类)的方法时,请使用前端. 通过搜索SO,可以找到一些现实的例子,包括ruby,module和prepend: > Overriding method by another defined in module (注意:我只提到方法,因为它们是最简单的图形,当涉及到继承和混合,但同样适用于其他功能.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |