Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Ruby's double-colon `::`?

What is this double-colon ::? E.g. Foo::Bar.

I found a definition:

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 good is scope (private, protected) if you can just use :: to expose anything?

like image 887
Meltemi Avatar asked Jun 09 '10 20:06

Meltemi


People also ask

What does :: mean in Ruby?

The use of :: on the class name means that it is an absolute, top-level class; it will use the top-level class even if there is also a TwelveDaysSong class defined in whatever the current module is.

What does colon mean 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 meaning of double colon?

The double colon ( :: ) may refer to: an analogy symbolism operator, in logic and mathematics. a notation for equality of ratios. a scope resolution operator, in computer programming languages.


2 Answers

:: is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup:

module SomeModule     module InnerModule         class MyClass             CONSTANT = 4         end     end end 

You could access CONSTANT from outside the module as SomeModule::InnerModule::MyClass::CONSTANT.

It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot .).

Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes

like image 126
mipadi Avatar answered Oct 18 '22 03:10

mipadi


This simple example illustrates it:

MR_COUNT = 0        # constant defined on main Object class module Foo   MR_COUNT = 0   ::MR_COUNT = 1    # set global count to 1   MR_COUNT = 2      # set local count to 2 end  puts MR_COUNT       # this is the global constant: 1 puts Foo::MR_COUNT  # this is the local constant: 2 

Taken from http://www.tutorialspoint.com/ruby/ruby_operators.htm

like image 29
Nader Avatar answered Oct 18 '22 03:10

Nader