--0016363104e91800b70499190f9c
Content-Type: text/plain; charset=ISO-8859-1

On Wed, Jan 5, 2011 at 6:10 AM, Konrad K. <konrad.krol89 / gmail.com> wrote:

> I was thinking of something similar to multiple inheritance and my
> expectaions was that all of local variables will be available in Child
> class.
> What I discovered that when you add
> include Parent1
> line to Child class @loc3 and @loc4 disappears.
> When you comment this line @loc3 and @loc4 are available in Child class.
>
> My question is why this work that way and how to get all of @loc
> available in Child class?
>
>
module Parent1
 def initialize
   @loc1  
   @loc2  
 end
end

class Parent2
 def initialize
   @loc3  
   @loc4  
 end

 def displayp2
   puts @loc3
   puts @loc4
 end
end

class Child < Parent2
 def displayc
   puts @loc1
   puts @loc2
   puts @loc3
   puts @loc4
 end
end


# You can see that when we ask the child for its initialize method,
# it finds the one that Parent2 has defined, then when we include Parent1,
# it gets inserted before Parent2 in the inheritance chain,
# and Child finds the one that Parent1 has defined.
c  hild.new
Child.ancestors       # [Child, Parent2, Object, Kernel, BasicObject]
c.method(:initialize) # #<Method: Child(Parent2)#initialize>

class Child
  include Parent1
end
Child.ancestors       # [Child, Parent1, Parent2, Object, Kernel,
BasicObject]
c.method(:initialize) # #<Method: Child(Parent1)#initialize>



# To get all the @loc, you can have the initialize method in Parent1 call
super,
# which will find the next one in the chain.
# note: super will forward any args that the method received,
# so you don't have to manually pass them on, unless you wish to change them
Child.new.instance_variables # [:@loc1, :@loc2]
module Parent1
  def initialize
    super
    @loc1  
    @loc2  
  end
end
Child.new.instance_variables # [:@loc3, :@loc4, :@loc1, :@loc2]

--0016363104e91800b70499190f9c--