Note that there are some explanatory texts on larger screens.

plurals
  1. POInconsistency about ruby 'main' object
    primarykey
    data
    text
    <p>Ruby is pretty consistent about classes and objects. However, when it comes to top-level method declaration, that rule somehow breaks down. For example, </p> <pre><code>$ puts self # =&gt; main $ puts self.class # =&gt; Object </code></pre> <p>However, the methods declared in the context of this <code>main</code> object are somehow available as private methods of class <code>Object</code>.</p> <p>Is there any logical explanation for this? I understand that this is very convenient as these methods appear as "stand-alone functions", but taking it just as "it just is so" breaks the otherwise consistent rules, as normally you have to define a method in the context of a class for it to be a method of that class. However, the <code>main</code> object is not class <code>Object</code>, nor is it a class at all.</p> <p><strong>Re-framing my question:</strong> In what scope does the method gets declared inside ruby's REPL? {class Object/ object main or module Kernel}</p> <p>Regarding private nature of methods declared in REPL, plz see the following example:</p> <pre><code>def my_method # "a method declared in REPL" puts "method called" end # calling my_method in REPL aka top-level scope my_method # =&gt; "method called" [].my_method # =&gt; private method `my_method' called for []:Array (NoMethodError) Array.my_method # =&gt; private method `my_method' called for Array:Class (NoMethodError) </code></pre> <p>Q: If my_method is defined as a private method under class Object, then why is self set to main instead of class Object. If someone says that its not under private scope, then why am I getting above mentioned error?</p>
    singulars
    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.
 

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