Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

namespaces - Ruby: what does :: prefix do?

I was reading through the source of Artifice and saw:

module Artifice
  NET_HTTP = ::Net::HTTP
  # ...
end

line: https://github.com/wycats/artifice/blob/master/lib/artifice.rb#L6

Why not just do Net::HTTP instead of ::Net::HTTP, i.e., what does it mean when you use :: as a prefix?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

To access Music::Record from outside of Music you would use Music::Record.

To reference Music::Record from Music::EightTrack you could simply use Record because it's defined in the same scope (that of Music).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...