Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby Classes within Classes (or Modules within Modules)
    primarykey
    data
    text
    <p>As I'm reading different Ruby books, I've noticed that Ruby classes can be defined within other Ruby classes or modules. Here's an example of a class within a class:</p> <pre><code>class Outerclass def foobar puts "FOOBAR" end class Innerclass def barfoo puts "BARFOO" end end end </code></pre> <p>Here's some code that I ran in IRB to try to understand this conceptually:</p> <pre><code>oc = Outerclass.new # =&gt; #&lt;Outerclass:0x00000100a46478&gt; Outerclass.instance_methods(false) # =&gt; [:foobar] ic = Outerclass::Innerclass.new # =&gt; #&lt;Outerclass::Innerclass:0x00000100a0b120&gt; ic = Outerclass::Innerclass.instance_methods(false) # =&gt; [:barfoo] </code></pre> <p>Here are my questions:</p> <ol> <li><p>When the ruby interpreter first encounters my Class definition code above, does it go through the methods I've written and store it somewhere? I know that the instance method "foobar" doesn't actually get run since there's no call being made to it within the Outerclass definition.</p></li> <li><p>Piggybacking off the 1st question, what about when Ruby encounters the class Innerclass? What happens here?</p></li> <li><p>In general, what are some reasons why you would want to have classes within classes? Are there any advantages to doing this?</p></li> <li><p>Does an instance of Outerclass know anything about the class Innerclass?</p></li> <li><p>Does an instance of Innerclass know anything about the class Outerclass?</p></li> </ol> <p>Appreciate any help you can provide!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload