What does ::
do in Foo::Bar
?
I thought it was related to encapsulation (private, protected), but it's not that when I looked at the 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.
Then :::
doesn't have to be there, does it? It doesn't restrict access, but it can be accessed anywhere by just filming
::
, but why is this there?
:::
is an operator related to namespace. It is used to access the item in the module or class.
For example,
module SomeModule
module InnerModule
class MyClass
CONSTANT = 4
end
end
end
When writing these codes, to access CONSTANT
outside SomeModule
SomeModule::InnerModule::MyClass::CONSTANT.
You have to share it.
The reason for writing :::
is not to restrict access, but to "prevent name conflicts between methods and classes."
Considering the case of joint development, there is a high possibility that the variable will have the same name. But should we check what other people are using? This is a very inefficient way. So you can write code freely on different namespaces to avoid conflicts.
MR_COUNT = 0 #constant (1) defined in the main object class
module Foo
MR_COUNT = 0 # Constant (2) as defined by Foo
::MR_COUNT = 1 # Set (1) to 1
MR_COUNT = 2 #(2) set to 2
end
puts MR_COUNT # (1)
puts Foo::MR_COUNT # (2)
606 Uncaught (inpromise) Error on Electron: An object could not be cloned
597 GDB gets version error when attempting to debug with the Presense SDK (IDE)
572 Understanding How to Configure Google API Key
567 Who developed the "avformat-59.dll" that comes with FFmpeg?
567 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.