ruby中的双冒号::

来源:互联网 发布:绝地求生怎么优化fps 编辑:程序博客网 时间:2024/05/16 01:06



双冒号是定义 name space 用的,或者叫 scope

当你使用 Foo::Bar 的时候,实际你是在找一个名字叫 Foo 的 namespace ,然后让它返回它里面的 Bar 参数 , 这个 Bar 可以是个常量,可以是个类,可以是个方法 (后两者在 Ruby 中可视为常量)

同理使用 FooBar::method1 的时候实际上是在要求返回 FooBar 这个 namespace 中 method1 这个「常量」的值。

使用 FooBar.method1 的时候则是在调用这个方法,当然返回结果是一样的,这里 :: 和 . 确实是可以互换不影响结果。但 :: 只能用来找 class method , instance method 就只能用 . 了

另外 :: 还能用来找真正的常量,比方这样

class Foo Bar = "hello" bar = "hello" end ========= Foo::Bar # => "hello" Foo::bar #  => 出错 Foo.Bar #  => 出错 Foo.bar #  => 出错

另外 :: 在开始位置则表示回到 root namespace ,就是不管前面套了几个 Module ,都算你其实写在最外层。

0 0