Ruby中的'Object'命名类

skr*_*rat 3 ruby class

如果我在模块内部使用Object作为我的类的名称,它有任何缺点吗?

module Some
  class Object; end
end
Run Code Online (Sandbox Code Playgroud)

Gre*_*ell 10

实际上,这段代码应该没有任何问题,因为它在一个模块中,因而命名空间.对于一个简单的测试:

module Some
  class Object
    def foo
      "bar"
    end
  end
end

Some::Object.new.foo # "bar"
Some::Object.new.class # "Some::Object"

# And it doesn't pollute the global namespaced Object class:
Object.new.respond_to?(:foo) # false
Run Code Online (Sandbox Code Playgroud)

但是,如果将Some包含在另一个类或模块中,其中Object将引用Some :: Object,则可能会造成混淆或模糊.但是,它仍然不会影响该类或模块之外的任何内容.