3

我遇到了两种调用文件类的方法:File::File

有人可以向我解释两者之间的区别,以及使用两者的不同原因吗?

4

2 回答 2

4

FileFile当前范围内的常量,而::File始终指Object::File.

p File
# File

p ::File
# File

module Another
  module File
  end

  p File
  # Another::File

  p ::File
  # File
end

Thus, the :: is analogous to the root of a file system and the module you are in is analogous to the current directory.

For object-oriented access to the current lexical scope, see Module.nesting.

于 2013-01-11T04:56:14.630 回答
2

当您引用具有短名称 ( File) 的类时,ruby 将使用最近范围内的类。看:

module MyModule
  class File
    def initialize *args; end
  end

  class Foo
    def initialize
      @file = File.new
    end
    attr_accessor :file
  end
end


f = MyModule::Foo.new
f.file.class # => MyModule::File

file2 = File.new 'newfile', 'w'
file2.class # => File

因此,与顶层代码Foo不同。File但是,如果Foo要使用此代码:

@file = ::File.new

然后它将使用“全局”File类,而不是本地到MyModule. 以类似的方式,我们可以MyModule::File在顶层使用

file2 = MyModule::File.new 'newfile', 'w'
于 2013-01-11T04:56:03.933 回答