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, called var, set 0.
    • declares objects of type a can asked dosomething, increases value of object's var 1.
  • defines class called b, special case of a

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

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -