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

nkm*_*nkm 4 ruby oop ruby-on-rails

我们可以使用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
Run Code Online (Sandbox Code Playgroud)

Ser*_*sev 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
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此帖子.

另请阅读:http://rhg.rubyforge.org/chapter04.html