ruby-on-rails – Ruby – 我们可以在类中的任何地方使用include
发布时间:2020-12-17 02:34:55 所属栏目:百科 来源:网络整理
导读:我们可以使用include语句在类中的任何位置包含一个模块,还是必须在类的开头? 如果我在类声明的开头包含模块,则方法重写按预期工作.如果我如下所述包括在底,为什么它不起作用? # mym.rbmodule Mym def hello puts "am in the module" endend# myc.rbclass M
我们可以使用include语句在类中的任何位置包含一个模块,还是必须在类的开头?
如果我在类声明的开头包含模块,则方法重写按预期工作.如果我如下所述包括在底,为什么它不起作用? # mym.rb module Mym def hello puts "am in the module" end end # myc.rb class Myc require 'mym' def hello puts "am in class" end include Mym end Myc.new.hello => am in class 解决方法
当您包含模块时,其方法不会替换此类中定义的方法,而是将它们注入到继承链中.因此,当您调用super时,将调用包含模块的方法.
它们与其他模块的行为方式几乎相同.当一个模块被包含时,它被放置在继承链的类的正上方,现有模块放在它上面.见例子: module Mym def hello puts "am in the module" end end module Mym2 def hello puts "am in the module2" super end end class Myc include Mym include Mym2 def hello puts "im in a class" super end end puts Myc.new.hello # im in a class # am in the module2 # am in the module 有关详细信息,请参阅this post. 另请阅读:http://rhg.rubyforge.org/chapter04.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |