Ruby: :: 前缀有什么作用? [英] Ruby: what does :: prefix do?
问题描述
我正在阅读 Artifice 的来源并看到:
I was reading through the source of Artifice and saw:
module Artifice
NET_HTTP = ::Net::HTTP
# ...
end
行:https://github.com/wycats/artifice/blob/master/lib/artifice.rb#L6
为什么不直接使用Net::HTTP
而不是::Net::HTTP
,即使用::
是什么意思code> 作为前缀?
Why not just do Net::HTTP
instead of ::Net::HTTP
, i.e., what does it mean when you use ::
as a prefix?
推荐答案
::
是作用域解析操作符.它的作用是确定可以在什么范围内找到模块.例如:
The ::
is the scope resolution operator. What it does is determines what scope a module can be found under. For example:
module Music
module Record
# perhaps a copy of Abbey Road by The Beatles?
end
module EightTrack
# like Gloria Gaynor, they will survive!
end
end
module Record
# for adding an item to the database
end
要从 Music
外部访问 Music::Record
,您可以使用 Music::Record
.
To access Music::Record
from outside of Music
you would use Music::Record
.
要从 Music::EightTrack
引用 Music::Record
您可以简单地使用 Record
因为它定义在相同的范围内(即音乐
).
To reference Music::Record
from Music::EightTrack
you could simply use Record
because it's defined in the same scope (that of Music
).
但是,要从 Music::EightTrack
访问负责与数据库交互的 Record
模块,您不能只使用 Record
,因为Ruby 认为你想要 Music::Record
.那时您将使用范围解析运算符作为前缀,指定全局/主范围:::Record
.
However, to access the Record
module responsible for interfacing with your database from Music::EightTrack
you can't just use Record
because Ruby thinks you want Music::Record
. That's when you would use the scope resolution operator as a prefix, specifying the global/main scope: ::Record
.
这篇关于Ruby: :: 前缀有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!