Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 202
ma11hew28 Avatar asked Feb 17 '11 18:02

ma11hew28


People also ask

What is :: in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.

What is prefix in Ruby?

The prefix of a string is either a string or a character with which the string begins. To delete the prefix of a string, we can use the delete_prefix() method in Ruby.


3 Answers

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.

like image 107
coreyward Avatar answered Oct 11 '22 17:10

coreyward


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.

like image 33
Guilherme Bernal Avatar answered Oct 11 '22 17:10

Guilherme Bernal


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

like image 37
yan Avatar answered Oct 11 '22 18:10

yan