then - ruby變量
Ruby的雙冒號(::)運算符使用差異 (2)
兩者之間有什麼區別嗎?
module Foo
class Engine < Rails::Engine
end
end
和
module Foo
class Engine < ::Rails::Engine
end
end
Ruby中的常量嵌套在文件系統中的文件和目錄中。 因此,常量由它們的路徑唯一標識。
與文件系統類比:
::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查找最接近的定義時,無論它是在當前範圍內還是在外部範圍內或外部外部範圍內等。