What does ::MyClass Ruby scope operator do?

后端 未结 2 1256
[愿得一人]
[愿得一人] 2020-12-10 15:28

What does the ::MyClass/MyModule scope operator do in Ruby, what is its purpose?

相关标签:
2条回答
  • 2020-12-10 15:30

    This explicitly refers to the MyClass in the global scope. If there is a MyClass in the global scope, but also a MyClass inside of SomeModule, referring to MyClass from inside of SomeModule will refer to MyClass inside of the module, not the global MyClass. Saying ::MyClass explicitly refers to the MyClass in the global scope.

    class MyClass
      def self.something
        puts "Global MyClass"
      end
    end
    
    module SomeModule
      class MyClass
        def self.something
          puts "SomeModule::MyClass"
        end
      end
    
      print "From the module: "
      MyClass.something
    
      print "Explicitly using global scope: "
      ::MyClass.something
    end
    
    print "From the global scope: "
    MyClass.something
    
    print "Explicitly using module scope: "
    SomeModule::MyClass.something
    
    0 讨论(0)
  • 2020-12-10 15:33

    "global scope" just means the constant is defined on the Object class. So ::SomeModule is shorthand for Object::SomeModule

    0 讨论(0)
提交回复
热议问题