Ruby中类名前的双冒号? [英] Double colons before class names in Ruby?

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

问题描述

我在 Rails 中看到很多在类名之前使用双冒号.

I have seen a lot usage of double colons in Rails before class names.

例如:

require ::File.expand_path('../config/environment',  __FILE__)

我知道 Module::Class::Constant 是什么意思,但是 ::Class 呢?

I know what Module::Class::Constant means, but ::Class ?

推荐答案

这意味着你引用了顶级命名空间中的常量File.在这样的情况下这是有道理的:

It means that you're referring to the constant File from the toplevel namespace. This makes sense in situations like this:

class MyClass #1
end

module MyNameSpace
  class MyClass #2
  end

  def foo # Creates an instance of MyClass #1
    ::MyClass.new # If I left out the ::, it would refer to
                  # MyNameSpace::MyClass instead.
  end
end

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

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