-3

在下面的示例中,我希望在实例化B时创建/设置类中的实例变量B。显然我不想去重新initialize定义A.

class A

  def initialize(a)
  end

  def initialize(a, b)
  end

end

class B < A
  # Here I want an instance variable created without
  # redefining the initialize methods

  @iv = "hey" #<-- Obviously does not work

  # And I don't want to have to do @iv |= "hey" all over the place

end
4

1 回答 1

2

我不确定你对定义初始化方法有什么反对,但这是应该这样做的。

class A
  def initialize a
    @a = a
  end

  attr_accessor :a
end

class B < A
  def initialize a, b
    @b = b
    super(a)
  end
  attr_accessor :b
end

b = B.new 1, 2

b.a # => 1
b.b # => 2
于 2012-11-19T07:57:57.307 回答