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