2012-07-09 80 views
6

什麼是這之間的區別:嵌套模塊定義和在ruby中使用::定義有什麼區別?

module Outer 
    module Inner 
    class Foo 
    end 
    end 
end 

這:

module Outer::Inner 
    class Foo 
    end 
end 

我知道,如果Outer前面沒有定義後者的例子是行不通的,但也有一些不變的其他差異範圍和我可以找到他們的說明SO或文檔(包括編程紅寶書)

+0

我覺得 「類A :: B :: MyClass的」 不工作,不是嗎? – davidrac 2012-07-09 11:04:09

+0

是的,它可以工作,但是class A :: B :: MyClass有什麼不同?結束'和'模塊A;模塊B; class MyClass;結束;結束;結束;'? – 2012-07-09 11:05:55

回答

3

至少有一個區別 - 不斷查找,檢查此代碼:

module A 
    CONST = 1 

    module B 
    CONST = 2 

    module C 
     def self.const 
     CONST 
     end 
    end 
    end 
end 

module X 
    module Y 
    CONST = 2 
    end 
end 

module X 
    CONST = 1 

    module Y::Z 
    def self.const 
     CONST 
    end 
    end 
end 

puts A::B::C.const # => 2, CONST value is resolved to A::B::CONST 
puts X::Y::Z.const # => 1, CONST value is resolved to X::CONST 
+0

因此,它使用詞法作用域作爲常量並「跳過」::當模塊定義正確時,正確嗎? – 2012-07-09 10:48:39

+0

我不知道他們的算法的細節,但它絕對看起來像那樣。知道這有助於你避免有時候調試地獄。我不知道2種模塊/類定義之間的其他區別。 – keymone 2012-07-09 10:51:23

+0

是的,這與Rails自動加載相結合可能導致一些地獄般的調試:) – 2012-07-09 11:03:08

7

由於keymone的answer我制定正確的谷歌查詢,發現這個:Module.nesting and constant name resolution in Ruby

使用::改變固定範圍分辨率

module A 
    module B 
    module C1 
     # This shows modules where ruby will look for constants, in this order 
     Module.nesting # => [A::B::C1, A::B, A] 
    end 
    end 
end 

module A 
    module B::C2 
    # Skipping A::B because of :: 
    Module.nesting # => [A::B::C2, A] 
    end 
end 
相關問題