module Api
module V1
class ABC
end
end
end
class Api::V1::ABC
end
这些声明类有什么不同吗?
有什么优缺点吗?
最佳答案
是的,在您执行 constant lookups 时会有所不同. Module::nesting
在这里会为您解决问题提供帮助。
module Api
module V1
class ABC
p Module.nesting
end
end
end
# >> [Api::V1::ABC, Api::V1, Api]
module Api
module V1
end
end
class Api::V1::ABC
p Module.nesting
end
# >> [Api::V1::ABC]
Module.nesting
返回在 Ruby 遍历 class/module 层次结构以查找常量之前搜索的词法封闭类/模块。
意思是,用下面的代码:
module Api
module V1
X = 12
end
end
X = 10
class Api::V1::ABC
p X
end
Api::V1::ABC.superclass # => Object
# >> 10
当常量查找时,它会首先搜索Module.nesting
给出的常量数组,如果没有找到,直到祖先链/包含的模块。这意味着遵循 Api::V1::ABC.ancestors
输出。
现在在上面的示例中,您可以看到打印了 X
的值,它是在 Object
中定义的,而不是在 API::V1< 中
。原因我上面说了。
现在来看下面的另一个例子:-
X = 10
module Api
module V1
X = 12
class ABC
p X
end
end
end
# >> 12
这里的常量查找将遵循数组 [Api::V1::ABC, Api::V1, Api]
。您可以看到输出为 12
,因为 Api::V1
中定义了常量 X
。
因此我们可以说 - 是的,这两个声明之间存在差异。
关于ruby - 使用::或模块声明类有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23298437/