Note that there are some explanatory texts on larger screens.

plurals
  1. POclass_variable_set gives `NameError: unintialized class variable in Object` when variable accessed
    primarykey
    data
    text
    <p>I'm doing the following, and expecting <code>TestClass.my_var</code> to return<code>"my_var_here"</code>:</p> <pre><code>irb(main):001:0&gt; def create_a_class class_name, my_var irb(main):002:1&gt; klass = Object.const_set class_name, Class.new irb(main):003:1&gt; klass.class_variable_set :@@my_var, my_var irb(main):004:1&gt; klass.instance_eval do irb(main):005:2* def my_var irb(main):006:3&gt; @@my_var irb(main):007:3&gt; end irb(main):008:2&gt; end irb(main):009:1&gt; klass irb(main):010:1&gt; end =&gt; nil irb(main):011:0&gt; create_a_class "TestClass", "my_var_here" =&gt; TestClass </code></pre> <p>Instead, I get this:</p> <pre><code>irb(main):012:0&gt; TestClass.my_var (irb):6: warning: class variable access from toplevel NameError: uninitialized class variable @@my_var in Object from (irb):6:in `my_var' from (irb):12 from C:/Ruby193/bin/irb:12:in `&lt;main&gt;' </code></pre> <p>What am I doing wrong? Any input would be appreciated.</p> <p>EDIT: I've tried doing it like this and it seems to work, but it doesn't really feel like The Ruby Way™ of doing it (also I'd rather not have those pesky warnings)</p> <pre><code>irb(main):001:0&gt; def create_a_class class_name, _my_var irb(main):002:1&gt; klass = Object.const_set class_name, Class.new irb(main):003:1&gt; klass.instance_eval do irb(main):004:2* @@my_var = _my_var irb(main):005:2&gt; def my_var irb(main):006:3&gt; @@my_var irb(main):007:3&gt; end irb(main):008:2&gt; end irb(main):009:1&gt; klass irb(main):010:1&gt; end =&gt; nil irb(main):011:0&gt; create_a_class "TestClass", "my_var_here" (irb):4: warning: class variable access from toplevel =&gt; TestClass irb(main):012:0&gt; TestClass.my_var (irb):6: warning: class variable access from toplevel =&gt; "my_var_here" </code></pre>
    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.
    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