Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby's def and instance_eval vs. class_eval
    primarykey
    data
    text
    <p>I'm reading the Metaprogramming section of <em>Programming Ruby 1.9</em> and I'm having trouble understanding what's going on <em>internally</em> between <code>class_eval</code>/<code>class_exec</code> vs. <code>instance_eval</code>/<code>instance_exec</code>.</p> <p>So first of all, my understanding is that <code>def</code> adds a method to the method table of <code>self</code> (the class object):</p> <pre><code>class A puts self # =&gt; A def foo; 42; end # added to the method table of self, so becomes an instance method end A.new.foo # =&gt; 42 </code></pre> <p>And if we use <code>class_eval</code>, we get the same behavior:</p> <pre><code>A.class_eval do puts self # =&gt; A def bar; 42; end # same as above end A.new.bar # =&gt; 42 </code></pre> <p>But somehow in the <code>instance_eval</code> case, things are different:</p> <pre><code>A.instance_eval do puts self # =&gt; A def baz; 42; end # added to the method table of an anonymous # singleton class of self, so becomes a class method end puts A.baz # =&gt; 42 s = 'string' s.instance_eval do ... end # same behavior, so now def creates an instance method </code></pre> <p>So I understand the functional difference between <code>class_eval</code> and <code>instance_eval</code>.</p> <p>But the contexts inside the <code>class_eval</code> and <code>instance_eval</code> blocks look <em>exactly</em> the same to me -- in particular, <code>self</code> points to the same object, and the <code>local_variables</code> are the same. So what's going on inside the blocks (internally) that's making <code>def</code> act different?</p> <p>Is there some piece of documentation I could read? The RDoc for <a href="http://ruby-doc.org/core/classes/Object.html#M000334" rel="noreferrer">instance_eval</a> and <a href="http://ruby-doc.org/core/classes/Module.html#M001650" rel="noreferrer">class_eval</a> doesn't help. Looking at the source, <a href="http://ruby-doc.org/core/classes/Object.src/M000334.html" rel="noreferrer">instance_eval</a> seems to set up a singleton class object whereas <a href="http://ruby-doc.org/core/classes/Module.src/M001650.html" rel="noreferrer">class_eval</a> doesn't -- but is this difference visible outside the C code, on the Ruby level?</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