What are the two colons in Ruby doing?

Asked 2 years ago, Updated 2 years ago, 126 views

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?

ruby syntax operator

2022-09-22 22:09

1 Answers

::: 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)


2022-09-22 22:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.