Ruby 的双冒号 (::) 运算符用法差异 [英] Ruby's double colon (::) operator usage differences

查看:92
本文介绍了Ruby 的双冒号 (::) 运算符用法差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别吗

module Foo
  class Engine < Rails::Engine
  end
end

module Foo
  class Engine < ::Rails::Engine
  end
end

推荐答案

Ruby 中的常量就像文件系统中的文件和目录一样嵌套.因此,常量由它们的路径唯一标识.

Constants in Ruby are nested like files and directories in filesystem. So, constants are uniquely identified by their paths.

以文件系统做类比:

::Rails::Engine #is an absolute path to the constant.
# like /Rails/Engine in FS.

Rails::Engine #is a path relative to the current tree level.
# like ./Rails/Engine in FS.

以下是可能错误的说明:

Here is the illustration of possible error:

module Foo

  # We may not know about this in real big apps
  module Rails
    class Engine 
    end
  end

  class Engine1 < Rails::Engine
  end

  class Engine2 < ::Rails::Engine
  end
end

Foo::Engine1.superclass
 => Foo::Rails::Engine # not what we want

Foo::Engine2.superclass
 => Rails::Engine # correct

这篇关于Ruby 的双冒号 (::) 运算符用法差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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