Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double colons before class names in Ruby?

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 ?

like image 281
omtr Avatar asked Jan 27 '11 16:01

omtr


People also ask

What does the double colon :: operator do in a class?

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 the :: in Ruby?

The :: is a unary operator and is used to access (anywhere outside the class or module) constants, instance methods and class methods defined within a class or module. Note: In Ruby, classes and methods may be considered constants too.

What do colons mean in Ruby?

What is symbol. Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.

What does double mean in Ruby?

Use the `!!` (Double-bang) Operator for Boolean Values In most programming languages, including Ruby, ! will return the opposite of the boolean value of the operand. So when you chain two exclamation marks together, it converts the value to a boolean.


1 Answers

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 
like image 111
sepp2k Avatar answered Oct 09 '22 08:10

sepp2k