Ruby-嵌套类和子类是一回事吗?

Mir*_*318 5 ruby inheritance

以下示例之间Nested和之间的区别是什么Child?是同一件事的不同语法吗?

class Parent
  class Nested
    ...
  end
end

class Child < Parent
  ...
end
Run Code Online (Sandbox Code Playgroud)

ucp*_*uzz 7

,他们是不同的.

嵌套:计算机外部的"处理器"类只能作为Computer :: Processor访问.嵌套为内部类(命名空间)提供上下文.对于ruby解释器Computer and Computer :: Processor只是两个独立的类.

 class Computer
  class Processor # To create an object for this class, this is the syntax Computer::Processor.new. The Outer class provides context
Run Code Online (Sandbox Code Playgroud)

Child:下面是类继承,Parent类的实例/类方法可用于Child.可以像这样Child.new/Parent.new实例化Child/Parent

class Child < Parent
Run Code Online (Sandbox Code Playgroud)

请注意,Processor可以通过访问Computer::Processor,只调用Processor将抛出一个错误.同样,调用Child很好,但调用Parent::Child会抛出一个警告(虽然它实际上运行正常).

  • 注意,嵌套在模块"M"中的类`C`以完全相同的方式引用:`M :: C`. (3认同)