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?

推荐答案

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

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

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

Ruby相关问答推荐

数组上的Ruby#unionreact 非常奇怪

使用 RSpec 测试嵌套哈希时随机排序数组的匹配

每次调用返回新的 REST 响应的 Ruby Rspec class_double

字符串长度多显示一个字符 - ruby

RSpec 是否有 python 类似功能来做 TDD?

Procs的绑定

Sinatra 与 EventMachine WebSockets 一起工作是否成功?

Simple_form:删除带有标签的内联复选框的外部标签

如何记录在 Ruby 程序中调用的每个方法?

VCRProxy:在 Capybara 内使用 VCR 记录 PhantomJS ajax 调用

比较ruby中的两个字符串

什么时候在 Ruby 中使用 Struct 比使用 Hash 更好?

如何在 Ruby 中创建私有类常量

不区分大小写的数组#include?

Ruby:更新哈希值的最简单方法是什么?

是什么让 Ruby 变慢了?

困惑,像python,ruby这样的语言是单线程的吗?不像说java? (对于网络应用程序)

如何将多个元素添加到数组中?

纯 Ruby 并发哈希

Ruby:从 Ruby 中的变量创建哈希键和值