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?
It is all about preventing definitions from clashing with other code linked in to your project. It means you can keep things separate.
For example you can have one method called "run" in your code and you will still be able to call your method rather than the "run" method that has been defined in some other library that you have linked in.
In Ruby, everything is exposed and everything can be modified from anywhere else.
If you're worried about the fact that classes can be changed from outside the "class definition", then Ruby probably isn't for you.
On the other hand, if you're frustrated by Java's classes being locked down, then Ruby is probably what you're looking for.
::
Lets you access a constant, module, or class defined inside another class or module. It is used to provide namespaces so that method and class names don't conflict with other classes by different authors.When you see
ActiveRecord::Base
in Rails it means that Rails has something likei.e. a class called
Base
inside a moduleActiveRecord
which is then referenced asActiveRecord::Base
(you can find this in the Rails source in activerecord-n.n.n/lib/active_record/base.rb)A common use of :: is to access constants defined in modules e.g.
The
::
operator does not allow you to bypass visibility of methods marked private or protected.