【问题标题】:Create inner-class object after executing outer-class's constructor in Ruby?在Ruby中执行外部类的构造函数后创建内部类对象?
【发布时间】:2019-07-03 15:20:13
【问题描述】:

我想为类中的内部类创建对象。所有内部类方法都使用一个公共变量,需要在创建外部类时对其进行初始化。

class A
    @x = nil
    @y = nil
    def initialize(x, y)
        @x = x
        @y = y
    end

    class B
        def func_b
            puts "x- #{@x} and y- #{@y} in class B"
        end
    end

    class C
        def func_c
            puts "x- #{@x} and y- #{@y} in class C"
        end
    end
end

我能够为 BC 之类的类创建对象

#1
b = A::B.new
#2
a = A
c = a::C.new

但我想在为BC 创建对象之前初始化A

类似

a = A.new(4,5)
b = a::C.new

但这似乎不起作用。我该怎么做。

【问题讨论】:

    标签: ruby class constructor inner-classes


    【解决方案1】:

    Ruby 中的嵌套模块和类主要是一种组织选择。比较一下

    class A; end
    class B; end
    

    还有这个

    class A
      class B; end
    end
    

    它们之间只有两个区别

    1. 在第二个例子中,你必须写A::B才能访问B
    2. 在第二个示例中,在B 中访问的常量将在A 中查找,然后再在顶级中查找

    如果您确实希望这些类的实例相关,则需要它们之间的子类和超类关系,即

    class B < A; end
    

    现在B 的实例可以访问A 中的方法和实例变量。请注意,这与嵌套无关,您可以将其定义为

    class A
      class B < A; end
    end
    

    但这只是组织上的差异。


    在一个完全独立的注释中,这个

    class A
      @x = nil
      @y = nil
    end
    

    做你认为它做的事。这是在A 本身上设置实例变量,即将A 视为A.singleton_class 的实例。如果您想要 Ainstances 的默认值,则必须在 initialize 中设置这些值:

    class A
      def initialize
        @x = nil
        @y = nil
      end
    end
    

    【讨论】:

      【解决方案2】:
      class A
          def initialize(x, y)
              @x = x
              @y = y
          end
      end
      
      class B < A
          def func_b
              puts "x- #{@x} and y- #{@y} in class B"
          end
      end
      
      class C < A
          def func_c
              puts "x- #{@x} and y- #{@y} in class C"
          end
      end
      
      c = C.new(4,5)
      c.func_c
      

      打印

      x- 4 and y- 5 in class C
      

      这似乎工作正常:)。

      【讨论】:

      • 这个“解决方案”与你所问的无关......你应该多阅读一些关于 OOP 的内容,因为你似乎不知道表达这些概念的正确语言。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2014-12-12
      • 2018-04-13
      相关资源
      最近更新 更多