Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think your confusion comes from the fact that def does not depend on the current self, you might think about it as being a "current class" that has it's own rules.</p> <p>Following your examples:</p> <pre><code>class A # defs here go to A puts self # =&gt; A class &lt;&lt; self #defs here go to A's eigenclass end end A.class_eval do #defs here go to A end A.instance_eval do #defs here go to A's eigenclass end s = "Hello World" class &lt;&lt; s #defs here go to s's eigenclass end </code></pre> <p>Here's the portion of the chapter that talks about the issue and it's pretty clear about the behaviour </p> <blockquote> <p>class_eval and instance_eval both set self for the duration of the block. However, they differ in the way they set up the environment for method definition. class_eval sets things up as if you were in the body of a class definition, so method definitions will define instance methods In contrast, calling instance_eval on a class acts as if you were working inside the singleton class of self. Therefore, any methods you define will become class methods.</p> </blockquote> <p>The only thing I think is worth adding is that you can call instance_eval in any object, not just classes, and the behaviour doesn't change but has different consequences.</p> <p>Some relevant reading:</p> <p><a href="http://blog.jayfields.com/2007/03/ruby-instanceeval-and-classeval-method.html" rel="nofollow noreferrer">Ruby: instance_eval and class_eval method definitions</a></p> <p><a href="http://www.pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming" rel="nofollow noreferrer">Chapter 4 of this most excelent series</a></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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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