下面例子中的 Nested
和 Child
有什么区别?是否只是同一事物的不同语法?
class Parent
class Nested
...
end
end
class Child < Parent
...
end
最佳答案
不,它们是不同的。
嵌套:Computer 之外的“Processor”类只能作为 Computer::Processor 访问。嵌套为内部类( namespace )提供上下文。对于 ruby 解释器 Computer 和 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
Child:下面是类继承,Parent类的实例/类方法对Child可用。 Child/Parent 可以这样实例化 Child.new/Parent.new
class Child < Parent
注意 Processor
只能被 Computer::Processor
访问,调用 Processor
会抛出一个错误。同样,调用 Child
是好的,但是调用 Parent::Child
会抛出警告(尽管它实际上运行正常)。
关于Ruby——嵌套类和子类是一回事吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44835938/