I have something like the following
class A
def initialize
@var = 0
end
def dosomething
@var+=1
end
end
class B < A
def initialize
super
end
def func
puts @var
end
end
The problem is when I call
a = A.new
a.dosomething
b = B.new
the value which @var returns is 0 how would I change my code so it would return the “new” value of var (1)?
Quick answer, for if you actually understand Classes, Inheritance and Objects : replace
@var(an instance variable, and therefore different inaandb) with@@var(a class variable, and therefore the same in all instances ofclass A).Otherwise, your question indicates you have a fundamental misunderstanding of what’s going on with classes, objects and inheritance.
Your code does the following:
A. This is essentially a blueprint from which you can create objects.Ais created, that object should be given it’s own private copy of an attribute, calledvar, which is set to0.Acan be asked todosomething, which increases the value of that object’svarby 1.B, which is a special case of anATherefore, in your second snippet, you create an object
a, which is anA. It has its own attribute calledvar, which is set to 0 and then incremented. You then createb, which is aB(and is therefore also anA).bhas its own attribute calledvar, separate froma‘svar, which is set to 0.