inheritance - Ruby- read the value of a variable in another class? -
i have following
class def initialize @var = 0 end def dosomething @var+=1 end end class b < def initialize super end def func puts @var end end
the problem when call
= a.new a.dosomething b = b.new
the value @var
returns 0
how change code return "new" value of var (1)?
quick answer, if understand classes, inheritance , objects : replace @var
(an instance variable, , therefore different in a
, b
) @@var
(a class variable, , therefore same in instances of class a
).
otherwise, question indicates have fundamental misunderstanding of what's going on classes, objects , inheritance.
your code following:
- defines class, called
a
. blueprint can create objects.- declares when object of type
a
created, object should given it's own private copy of attribute, calledvar
, set0
. - declares objects of type
a
can askeddosomething
, increases value of object'svar
1.
- declares when object of type
- defines class called
b
, special case ofa
therefore, in second snippet, create object a
, a
. has own attribute called var
, set 0 , incremented. create b
, b
(and therefore a
). b
has its own attribute called var
, separate from a
's var
, set 0.
Comments
Post a Comment