title: Use method arguments inside class definition (Ruby)
body: <p>I am attempting to add a method to all objects which allows adding variables to instances on the fly. However, I have run into the issue that when I begin the <code>class</code> block, the method arguments are out of scope and thus no longer available.</p>
  
  <p>How might I access the method arguments from within the <code>class</code> block? Or is there a better way to do this?</p>
  
  <pre><code>class Object
      def addvar(name, value = nil)
          puts name # =&gt; "test"
          class &lt;&lt; self
              puts name # =&gt; returns nil!
              attr_accessor name # =&gt; nil is not a symbol nor a string (TypeError)
          end
          self.instance_variable_set("@" + name.to_s, value)
      end
  end
  
  x = Object.new
  x.addvar("test", 3)
  </code></pre>
  
  <p>It's also possible to use eval with string substitution, but that's something I would rather avoid for security reasons:</p>
  
  <pre><code>class Object
      def addvar(name, value = nil)
          eval("class &lt;&lt; self
                    attr_accessor :#{name}
               end
               self.#{name} = #{value}")
      end
  end
  
  x = Object.new
  x.addvar(:test, 3)
  puts x.test
  </code></pre>