class A
def initialize(var)
@var = var
end
end
class B < A
def initialize
end
def test
puts @var
end
end
a = A.new('hello')
b = B.new
b.test
此代码不起作用,因为 b
继承自 A
而不是 a
。
在 Ruby(或 Rails)中,我如何获得这种行为?继承对共享方法有用,是否也可以共享数据?
更新
这个问题有点困惑,所以我会尽力澄清。
我希望 B
的实例不仅从类 A
继承,而且还从 A
的实例继承。这样,我就可以做这样的事情:
a1 = A.new('one')
a2 = A.new('two')
b1 = a1.B.new # not ruby syntax, but this is why I'm asking the question
b2 = a2.B.new
b3 = a2.B.new
b3.test
#=> 'two'
b2.test
#=> 'two'
b1.test
#=> 'one'
最佳答案
实现目标的一种快速方法是使用鲜为人知的 SimpleDelegator类:
class A
attr_reader :var
def initialize(var)
@var = var
end
end
require 'delegate'
class B < SimpleDelegator
def test
puts var
end
end
a1 = A.new('one')
a2 = A.new('two')
b1 = B.new(a1)
b1 = B.new(a1)
b2 = B.new(a2)
b3 = B.new(a2)
b3.test
#=> 'two'
b2.test
#=> 'two'
b1.test
#=> 'one'
这blog article (“将您的工作转发给 Ruby 中的其他对象的 5 种方式”)您可能会感兴趣。
关于ruby-on-rails - Ruby——使用父实例变量的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58060649/