Ruby的双冒号`::`是什么? [英] What is Ruby's double-colon `::`?

查看:205
本文介绍了Ruby的双冒号`::`是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个双冒号::是什么?例如. Foo::Bar.

What is this double-colon ::? E.g. Foo::Bar.

我找到了定义:

::是一元运算符,它允许:在类或模块内定义的常量,实例方法和类方法,可以从类或模块之外的任何位置进行访问.

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?

推荐答案

::基本上是一个名称空间解析运算符.它允许您访问模块中的项目或类中的类级别的项目.例如,假设您有以下设置:

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

您可以像SomeModule::InnerModule::MyClass::CONSTANT一样从模块外部访问CONSTANT.

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

相关说明:如果要返回顶级名称空间,请执行以下操作::: SomeModule – Benjamin Oakes

Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes

这篇关于Ruby的双冒号`::`是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆