Ruby - 我们可以在类的任何位置使用 include 语句吗?

4

我们可以在类的任何位置使用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
1个回答

6
当您包含一个模块时,它的方法不会替换定义在此类中的方法,而是将它们注入到继承链中。因此,当您调用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

更多信息请参见此文章

还需阅读:http://rhg.rubyforge.org/chapter04.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接