2012-05-27 37 views
5

我正在嘗試將某個模塊混合到一個類中,並且我希望某些方法表現爲類方法,其他方法表示爲實例方法。class <<模塊中的表示法

不過,我不希望這兩個includeextend模塊。我寧願只是include而已。

當我換我想在這個符號類的方法方法,它的工作原理:

class << 
    # ... 
end 

然而,當我使用這個符號不工作:

class << self 
    # ... 
end 

我懷疑self關鍵字正在建立對模塊的顯式綁定,而不是它被混入的類。但我還沒有看到任何文檔建議在使用class <<表示法時關閉self關鍵字。

有誰知道這是怎麼回事?


更新:這是爲了更清楚一些示例代碼:

module M 
    class << 
    def class_method 
     puts "From inside the class_method" 
    end 
    end 

    def instance_method 
    puts "From inside the instance_method" 
    end 
end 

class Object 
    include M 
end 

class C 
end 


C.class_method 

obj = C.new 
obj.instance_method 
+1

呵呵,我錯過了什麼嗎? 'class << end'是一個語法錯誤。 – sepp2k

回答

6

class <<必須總是後面跟着一個對象。只是class <<; end是一個語法錯誤。在你的情況下,它看起來像它的工作原理因爲以下的原因:

class << 
    def class_method 
    puts "From inside the class_method" 
    end 
end 

相同

class << def class_method 
    puts "From inside the class_method" 
    end 
end 

這是一樣的

temp = def class_method 
    puts "From inside the class_method" 
end 
class << temp 
end 

這是一樣的

def class_method 
    puts "From inside the class_method" 
end 
class << nil 
end 

這是t他相同

def class_method 
    puts "From inside the class_method" 
end 

當然,這實際上並沒有定義一個類的方法。它定義了一個實例方法。

+0

大聲笑。這就解釋了爲什麼「表觀」類方法需要在Object中工作。它實際上是一個單例實例方法。工作很好。 – Nathan

0

呀,如果你希望得到您的模塊在一個真正的self你應該使用includedcallback。像這樣的事情指向你正確的方向:

module Bar 
    def self.included(base) 
    class << base 
     def class_method 
     "class_method" 
     end 
    end 
    end 
end 

class Foo 
    include Bar 
end 


p Foo.class_method # => "class_method" 
+0

我相信這就是他想要真正解決他的問題的方法,但是它並沒有回答「class <<'與class'self'相比的實際問題。 –

+0

像@ sepp2k說'class << end'是一個語法錯誤。所以我實際上不知道Nathan是什麼意思:( –

+0

)感謝納什,我知道包含的方法,但發現離開自己似乎達到了類似的效果。我沒有得到語法錯誤,並嘗試過ruby 1.8和1.9.3 - 我會稍微發佈一個完整的代碼示例供其他人試用 – Nathan

相關問題