Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby metaclass madness
    primarykey
    data
    text
    <p>I'm stuck. I'm trying to dynamically define a class method and I can't wrap my head around the ruby metaclass model. Consider the following class:</p> <pre><code>class Example def self.meta; (class &lt;&lt; self; self; end); end def self.class_instance; self; end end Example.class_instance.class # =&gt; Class Example.meta.class # =&gt; Class Example.class_instance == Example # =&gt; true Example.class_instance == Example.meta # =&gt; false </code></pre> <p>Obviously both methods return an instance of Class. But these two instances are not the same. They also have different ancestors:</p> <pre><code>Example.meta.ancestors # =&gt; [Class, Module, Object, Kernel] Example.class_instance.ancestors # =&gt; [Example, Object, Kernel] </code></pre> <p>What's the point in making a difference between the metaclass and the class instance?</p> <p>I figured out, that I can <code>send :define_method</code> to the metaclass to dynamically define a method, but if I try to send it to the class instance it won't work. At least I could solve my problem, but I still want to understand why it is working this way.</p> <p><em>Update Mar 15, 2010 13:40</em></p> <p>Are the following assumptions correct.</p> <ul> <li>If I have an instance method which calls self.instance_eval and defines a method, it will only affect the particular instance of that class.</li> <li>If I have an instance method which calls self.class.instance_eval (which would be the same as calling class_eval) and defines a method it will affect all instances of that particular class resulting in a new instance method.</li> <li>If I have a class method which calls instance_eval and defines a method it will result in a new instance method for all instances.</li> <li>If I have a class method which calls instance_eval on the meta/eigen class and defines a method it will result in a class method.</li> </ul> <p>I think it starts to make sense to me. It would certainly limit your possibilities if self inside an class method would point to the eigen class. If so it would not be possible to define an instance method from inside a class method. Is that correct?</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.
    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