Val*_*cev 6 ruby scope constants
这有什么区别:
module Outer
module Inner
class Foo
end
end
end
Run Code Online (Sandbox Code Playgroud)
还有这个:
module Outer::Inner
class Foo
end
end
Run Code Online (Sandbox Code Playgroud)
我知道如果Outer之前没有定义,后一个例子将不起作用,但是在常量范围内还存在一些其他差异,我可以在SO或文档中找到它们的描述(包括编程Ruby书)
感谢keymone的回答,我制定了正确的Google查询并发现了这一点:Ruby中的Module.nesting和常量名称解析
使用::更改恒定范围分辨率
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
Run Code Online (Sandbox Code Playgroud)
至少有一个区别 - 常量查找,请检查以下代码:
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
Run Code Online (Sandbox Code Playgroud)