Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>EDIT:</strong> below code was tested with 1.8.7 and 1.9.1...it seems the situation is different again with 1.9.2 :/</p> <p>The situation actually isn't that straight forward. There are differences in behaviour depending on whether you're using 1.8 or 1.9 and whether you're using <code>class_eval</code> or <code>instance_eval</code>.</p> <p>The examples below detail the behaviour in most situations. </p> <p>I also included the behaviour of constants, for good measure, as their behaviour is similar to, but not exactly the same as, class variables.</p> <h2>Class variables</h2> <p><strong><code>class_eval</code> in Ruby 1.8:</strong></p> <pre><code>class Hello @@foo = :foo end Hello.class_eval { @@foo } #=&gt; uninitialized class variable </code></pre> <p><strong><code>class_eval</code> in Ruby 1.9:</strong></p> <pre><code>Hello.class_eval { @@foo } #=&gt; :foo </code></pre> <p>So class variables <strong>are</strong> looked up in 1.9 (but not in 1.8) when using <code>class_eval</code> </p> <p><strong><code>instance_eval</code> in Ruby 1.8 <em>and</em> 1.9</strong></p> <pre><code>Hello.instance_eval { @@foo } #=&gt; uninitialized class variable Hello.new.instance_eval { @@foo } #=&gt; uninitialized class variable </code></pre> <p>It appears class variables are <strong>not</strong> looked up in 1.8 <strong>or</strong> 1.9 when using <code>instance_eval</code></p> <p>What is also interesting is the case for <strong>constants</strong>:</p> <h2>Constants</h2> <p><strong><code>class_eval</code> in Ruby 1.8</strong></p> <pre><code>class Hello Foo = :foo end Hello.class_eval { Foo } #=&gt; uninitialized constant </code></pre> <p><strong><code>class_eval</code> in Ruby 1.9</strong></p> <pre><code>Hello.class_eval { Foo } #=&gt; :foo </code></pre> <p>So, as with class variables, constants are looked up in 1.9 but <strong>not</strong> in 1.8 for <code>class_eval</code></p> <p><strong><code>instance_eval</code> in Ruby 1.8</strong></p> <pre><code>Hello.instance_eval { Foo } #=&gt; uninitialized constant Hello.new.instance_eval { Foo } #=&gt; uninitialized constant </code></pre> <p><strong><code>instance_eval</code> in Ruby 1.9</strong></p> <pre><code>Hello.instance_eval { Foo } #=&gt; uninitialized constant Hello.new.instance_eval { Foo } #=&gt; :foo </code></pre> <p>It appears that constant lookup is not quite analogous to class variable look up for Ruby 1.9. A <code>Hello</code> instance <strong>does</strong> get access to the constant while the <code>Hello</code> class does not.</p>
 

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