98

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?

3
  • 16
    I searched for this topic using the phrase "leading colons" and didn't find it initially; hopefully this comment will change that. :) Aug 30, 2011 at 19:41
  • @NathanLong Interesting idea. Did it work? Please report back. Apr 9, 2015 at 17:54
  • 1
    @NathanLong It worked!
    – coreyward
    May 18, 2015 at 13:49

3 Answers 3

243

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.

1
  • 11
    Excellent answer. FYI don't worry about random down votes. There are far more meaningful things in life. Apr 9, 2015 at 20:19
16
module A
  def self.method; "Outer"; end
end
module B
  module A
    def self.method; "Inner"; end
  end
  A.method   # => "Inner"
  ::A.method # => "Outer"
end

On the specific case of Artifice, at line 41 of the file that you've shown is defined a inner Net module. To keep acess to the outer Net module, it uses ::Net.

1
  • Can we use multiple :: prefixes to move to one more scope level or :: means the very top/global level? For ex.: ::::A.method (looks really weird). Thank you.
    – belgoros
    May 12, 2022 at 16:10
13

A :: operator refers to the global scope instead of local.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.