30

有没有区别

module Foo
  class Engine < Rails::Engine
  end
end

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

2 回答 2

52

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
于 2012-05-07T13:16:37.027 回答
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 会查找最接近的定义,无论它是在当前范围内、外部范围内还是外部外部范围等。

于 2014-02-26T15:25:35.487 回答