Ruby class 的语法

Syntax of a Ruby class

Rubyclass下面declaration/definition后面的format/syntax是什么?我不明白 class 名称中使用的冒号 (:)。这说明什么?

class ::Chef::Recipe
  include ::Opscode::ChefClient::Helpers
end

这来自 here

我熟悉以下定义 Ruby class 的方法:

class ClassName
   CONSTANT = Z
  ....methods...

end

而且我知道常量被称为 ClassName::Z,但是上面的声明方式对我来说是新的,我在哪里可以找到关于声明 ruby class 的文档所以。

首字母 :: 表示 "even though we might be lexically inside a class or module, define this new class from the top level namespace"。当您在常量名称的开头使用它时,即使您在另一个模块或 class 范围内,您引用​​(或创建)的常量也不在该范围内,而是在顶部级别(这些常量可以通过打印 Object.constants

列出

请注意,“<”之后的文本(对于超级class)可以是任何表达式,其中return是一个Class对象(在编译时计算)。您甚至可以使用一个函数来 return superclass.

module Foo
  class Bar
  end

  class ::Baz
  end
end

定义 Foo::BarBaz(不是 Foo::Baz)。

它类似于目录的工作方式:给定存在 /foo,并且当前目录为 /

cd foo
mkdir bar
mkdir /baz

创建 /foo/bar/baz(不是 /foo/baz)。

并且,这是一个如何查找常量的示例:

A = 1

module X
  A = 'hello'

  class Y
    A = [1, 2, 3]

    def show
      p A
      p ::A
    end
  end

end

X::Y.new.show

--output:--
[1, 2, 3]
1