在实例上创建实例变量而不使用`initialize`方法

时间:2012-11-19 07:53:53

标签: ruby

在下面的示例中,我希望在实例化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

1 个答案:

答案 0 :(得分: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