2011-06-08 141 views
2

請解釋下面爲什麼self用於def self.included (klass)Ruby中的模塊

module A 
    def self.included(klass) 
    puts "A -> #{klass}" 
    puts A 
    puts self 
    end 
end 

class X 
    include A 
end 

回答

4

通過寫def self.included正在定義是單身類模塊A.一般的一部分的方法,單方法只能通過做A.included()稱爲但是這種單方法具有使Ruby解釋器,以一個特殊的名字included當模塊被包含到一個類中時調用。

模塊中的常規方法(使用def foo定義)只能在模塊被包含在其他內容中才能調用。

1

這是如何聲明可以直接調用的模塊方法。通常,在模塊中定義的方法只有在其他類或模塊包含它們時纔可用,如本例中的類X.

module Example 
    def self.can_be_called 
    true 
    end 

    def must_be_included 
    true 
    end 
end 

在這種情況下,你會看到這些結果:

Example.can_be_called 
# => true 

Example.must_be_included 
# => NoMethodError: undefined method `must_be_included' for Example:Module 

self聲明的方法尚未在包含它的類或模塊合併,雖然。它們是特殊用途的。