Ruby的双冒号(::)运算符使用差异

时间:2012-05-07 13:13:25

标签: ruby

之间有什么区别吗?
module Foo
  class Engine < Rails::Engine
  end
end

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

2 个答案:

答案 0 :(得分:49)

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

与文件系统进行类比:

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

以下是可能出错的说明:

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

答案 1 :(得分:5)

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

这不太正确!

我们举个例子:

module M
  Y = 1
  class M
    Y = 2
    class M
      Y = 3
    end
    class C
      Y = 4
      puts M::Y
    end
  end
end

# => 3

module M
  Y = 1
  class M
    Y = 2
    class C
      Y = 4
      puts M::Y
    end
  end
end

# => 2

module M
  Y = 1
  class M
    Y = 2
    class M
      Y = 4
      puts M::Y
    end
  end
end

# => 4

所以当你说M :: Y ruby​​查找最接近的定义时,无论它是在当前范围,外部范围还是外部范围等内。