Ruby的双冒号(::)运算符用法差异

有什么区别吗?

module Foo class Engine < Rails::Engine end end 

 module Foo class Engine < ::Rails::Engine end end 

Ruby中的常量嵌套为文件系统中的文件和目录。 所以,常数是由它们的path唯一标识的。

用文件系统来比喻一下:

 ::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 
 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时,ruby会查找最接近的定义,不pipe它是在当前范围内还是在外部范围内还是外部范围外