Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's double colon (::) operator usage differences

Tags:

ruby

Is there any difference between

module Foo   class Engine < Rails::Engine   end end 

and

module Foo   class Engine < ::Rails::Engine   end end 
like image 939
CuriousMind Avatar asked May 07 '12 13:05

CuriousMind


People also ask

What do two colons mean in Ruby?

operator is used to access the method of a class. Double colon operator. Double colon ( : ) operator is use to access the constants, class methods and instance methods defined within a class or module to anywhere outside the class or module.

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 are colons used for in Ruby?

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 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.


1 Answers

Constants in Ruby are nested like files and directories in filesystem. So, constants are uniquely identified by their paths.

To draw an analogy with the file system:

::Rails::Engine #is an absolute path to the constant. # like /Rails/Engine in FS.  Rails::Engine #is a path relative to the current tree level. # like ./Rails/Engine in FS. 

Here is the illustration of possible error:

module Foo    # We may not know about this in real big apps   module Rails     class Engine      end   end    class Engine1 < Rails::Engine   end    class Engine2 < ::Rails::Engine   end end  Foo::Engine1.superclass  => Foo::Rails::Engine # not what we want  Foo::Engine2.superclass  => Rails::Engine # correct 
like image 100
Flexoid Avatar answered Sep 22 '22 01:09

Flexoid