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
This code doesn't work, because b inherits from A but not a.
In Ruby (or Rails), how do I get this kind of behavior? Inheritance is useful for sharing methods, can it also share data?
UPDATE
This question is a bit confusing, so I will try to clarify.
I want instances of B to inherit not only from the class A, but also from an instance of A. That way, I could do something like this:
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'
initializeinAclass so now it doesn't set@varinstance variable. What are you trying to achieve? What do you mean by trying to achieve 'parent's data'? Instance variables only live on instances, not on classes (well they do, but it's a different case then).@varis updated in the context ofb? Shoulda.testchange then too?A.