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?
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.
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.
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.
::
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With