Ruby 双冒号在模块内做什么?
我正在查看以下代码:Ruby 双冒号在模块内做什么?,ruby,module,Ruby,Module,我正在查看以下代码: module Tag def sync_taggings_counter ::Tag.find_each do |t| # block here end end end 我被Tag模块中的::Tag弄糊涂了 我知道双冒号用于命名类/模块中的空间类和模块。但我从未见过像上面那样使用它。它到底是什么意思?它是一个范围修饰符。在常量(标记)前面加上一个双冒号可以确保查找的是根/全局名称空间,而不是当前模块 例如 如果Ruby在本地模块中找
module Tag
def sync_taggings_counter
::Tag.find_each do |t|
# block here
end
end
end
我被Tag模块中的::Tag
弄糊涂了
我知道双冒号用于命名类/模块中的空间类和模块。但我从未见过像上面那样使用它。它到底是什么意思?它是一个范围修饰符。在常量(
标记
)前面加上一个双冒号可以确保查找的是根/全局名称空间,而不是当前模块
例如
如果Ruby在本地模块中找不到引用的常量,则通常不需要前缀,因为Ruby会自动在全局名称空间中查找。因此,如果Foo模块中不存在
Bar
,那么Bar.greet
和::Bar.greet
也会做同样的事情。我错了。看看这个问题:
module Foo
class Bar
def self.greet
"Hello from the Foo::Bar class"
end
end
class Baz
def self.scope_test
Bar.greet # Resolves to the Bar class within the Foo module.
::Bar.greet # Resolves to the global Bar class.
end
end
end
class Bar
def self.greet
"Hello from the Bar class"
end
end