Double colons before class names in Ruby?

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


I have seen a lot usage of double colons in Rails before class names.

For example:

require ::File.expand_path('../config/environment',  __FILE__)

I know what Module::Class::Constant means, but ::Class ?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

It means that you're referring to the constant File from the toplevel namespace. This makes sense in situations like this:

class MyClass #1
end

module MyNameSpace
  class MyClass #2
  end

  def foo # Creates an instance of MyClass #1
    ::MyClass.new # If I left out the ::, it would refer to
                  # MyNameSpace::MyClass instead.
  end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomtrView Question on Stackoverflow
Solution 1 - Ruby on-Railssepp2kView Answer on Stackoverflow