问题描述
我正在阅读 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
,即当您使用::
作为前缀时是什么意思?
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
,因为它是在同一范围(Music
的)中定义的.
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:::前缀有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!