【问题标题】:How does Ruby handle inheritance for nested classes?Ruby 如何处理嵌套类的继承?
【发布时间】:2011-07-19 12:53:31
【问题描述】:

在以下测试用例中:

class Package
    class Component
        def initialize
            p [:initialize,self]
        end
    end
end

class Package_A < Package
end

class Package_B < Package
end

# Why are the following components of type Package and not Package_A and Package_B
component=Package_A::Component.new
p component

component=Package_B::Component.new
p component

结果:

[:initialize, #<Package::Component_1:0x2c0a8f8>]
#<Package::Component:0x2c0a8f8>
[:initialize, #<Package::Component_1:0x2c0a5b0>]
#<Package::Component:0x2c0a

如何获取特定的 Package_A.component 和 Package_B.component?

【问题讨论】:

    标签: ruby inheritance nested-class


    【解决方案1】:

    Component 类在 Package 中声明,所以看起来是正确的。 :: 告诉在Package_A 的范围内查找名称Component。由于那里没有Component,它会查找超类。

    这个例子展示了如何实现你想要的。可能有更简单的方法,我很高兴看到它。

    class Package
      class Component
        def foo
          puts "bar"
        end
      end
    end
    
    class Pack_a < Package
    end
    
    Pack_a::Component.new.foo
    #=> bar
    # as expected, though we actually have Package::Component
    
    class Pack_b < Package
      class Component
      end
    end
    
    Pack_b::Component.new.foo
    #=> NoMethodError: undefined method 'foo' for Pack_b::Component
    # this error is because Pack_b::Component has nothing to do with Package::Component
    
    class Pack_c < Package
      class Component < Package::Component
      end
    end
    
    Pack_c::Component.new.foo
    #=> bar
    # as expected
    
    Pack_c::Component.new
    #=> Pack_c::Component
    # this Component is a subclass of Package::Component
    

    这个 more-less 应该解释作用域在这种情况下是如何工作的。希望这会有所帮助。

    【讨论】:

    • 感谢@Sorrow 提供上述示例...我用它来解决我的应用程序问题。也许有人会尝试支持 inheritable_nested_class Class1,Class2... 例如:inheritable_nested_class 组件这将导致上述样板自动生成在从具有所述指令的类继承的子类中。它会在高级元编程课程中做出很好的分配:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多