title: Ruby - including single module multiple times and ancestry hierarchy
body: <p>I'm reading 'Metaprogramming Ruby' right now and writing some code at the same time to clarify the concepts. I've read that when you include/prepend a single module multiple times, all further inclusions won't change the place of said module in the ancestry chain.</p>
  
  <p>I wrote some code that works in a way that I did not expect - what actually happens there?</p>
  
  <pre><code>module GreatGrandfather; end
  
  module Grandfather
    include GreatGrandfather
  end
  
  module Father
    include Grandfather
    prepend GreatGrandfather
  end
  
  module Son
    include Father
  end
  
  Son.ancestors # =&gt; [Son, Father, Grandfather, GreatGrandfather]
  </code></pre>
  
  <p>I've assumed that when I run <code>Son.ancestors</code>, Son would include Father, Father would include Grandfather and prepend GreatGrandfather and the ancestry tree would be set to <code>[Son, GreatGrandfather, Father, Grandfather]</code>. Obviously that didn't happen.</p>
  
  <p>Once Son includes Father, it starts to look in the Father module and finds <code>include Grandfather</code> and <code>prepend GratGrandfather</code>. Does it actually 'go into' <code>Grandfather</code> where it includes GreatGrandfather, and only then executes the <code>prepend GreatGrandfather</code> line (and ignores it because it already exists in the ancestry)? </p>
  
  <p>Truth be told, I doubt I will get much use out of it, but it won't hurt to know how exactly the modules 'chain' each other.</p>
  
  <p>@edit - I've played around with it a bit more, and it doesn't seem that my intuition is right in either case. I've included a picture of the two ways I thought it could go, instruction after instruction, about creating the inheritance hierarchy - the one that appears to occur in the picture goes against the original example given, so neither #1 or #2 can be happening.</p>
  
  <p>Modified example code (only GreatGrandfather changed)  </p>
  
  <pre><code>module GreatGrandfather
    include Grandfather
  end
  
  module Grandfather
    include GreatGrandfather
  end
  
  module Father
    prepend GreatGrandfather
    include Grandfather
  end
  
  module Son
    include Father
  end
  
  Son.ancestors # =&gt; Son, GreatGrandfather, Father, Grandfather
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/aPlUa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aPlUa.png" alt="enter image description here"></a></p>
  
  <p>in summary - I still have no idea how it happens</p>