2012-05-07 1 views

答えて

47

定数との間の差です。したがって、定数はパスによって一意に識別されます。ファイルシステムとのアナロジー描くように

:ここ

::Rails::Engine #is an absolute path to the constant. 
# like /Rails/Engine in FS. 

Rails::Engine #is a path relative to the current tree level. 
# like ./Rails/Engine in FS. 

は、可能なエラーの例です:

module Foo 

    # We may not know about this in real big apps 
    module Rails 
    class Engine 
    end 
    end 

    class Engine1 < Rails::Engine 
    end 

    class Engine2 < ::Rails::Engine 
    end 
end 

Foo::Engine1.superclass 
=> Foo::Rails::Engine # not what we want 

Foo::Engine2.superclass 
=> Rails::Engine # correct 
+0

右。だから、 'Module Foo'という名前でモジュールからRails :: Engineを呼び出すと、' Foo :: Rails :: Engine'と解釈されるかもしれません。私はこのようなエラーを時々見つけ、インクルードの前に追加の '::'を追加しなければなりませんでした。 –

+1

ファイルシステムの類推は素晴らしいです!ありがとう – CuriousMind

+5

これはPaolo Perrottaの "Metaprogramming Ruby"という本から引用されたものです。 Rubyの知識を深める非常に便利な本。 – Flexoid

5
Rails::Engine #is a path relative to the current tree level. 
# like ./Rails/Engine in FS. 

これはかなり真実ではありません!

はのは、例を持ってみましょう:あなたが言うとき、それは現在のスコープまたは外側のスコープまたは外側の外側のスコープなどの内部にある場合

module M 
    Y = 1 
    class M 
    Y = 2 
    class M 
     Y = 3 
    end 
    class C 
     Y = 4 
     puts M::Y 
    end 
    end 
end 

# => 3 

module M 
    Y = 1 
    class M 
    Y = 2 
    class C 
     Y = 4 
     puts M::Y 
    end 
    end 
end 

# => 2 

module M 
    Y = 1 
    class M 
    Y = 2 
    class M 
     Y = 4 
     puts M::Y 
    end 
    end 
end 

# => 4 

だからM :: Yルビーは、最も近いdefintionのために関係なく検索します

+0

これはRubyですか? 2.2.4では、私は3、3、4と多くの "トップレベルの定数は既に参照されている警告" –