2012-01-05 36 views
4

我們可以使用include語句在課程中的任何地方包含模塊,還是必須在課程的開頭?Ruby - 我們可以在類中的任何地方使用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 

回答

5

當你有一個模塊,它的方法做替換這個類中定義的方法,而是他們被注入繼承鏈。因此,當您撥打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

相關問題