title: In Ruby, is there no way to dynamically define a local variable in the current context?
body: <p>I'm wondering if there is a method which will allow me to dynamically define a previously undefined variable in the current context. For example:</p>
  
  <pre><code>foo # =&gt; NameError: undefined method or local variable ...
  # Some method call which sets foo = 1 in the local context
  foo # =&gt; 1
  </code></pre>
  
  <p>Put another way, given that <code>foo</code> is undefined, I'm looking for any code that would let me define the local variable <code>foo</code> without using the <code>foo</code> variable (e.g. if I had some other variable <code>bar</code> whose value was <code>:foo</code> and I had to rely on that to set the value of <code>foo</code>).</p>
  
  <p>It seems that <code>eval('foo = 1')</code> or <code>eval('foo = 1', binding)</code> or, in Ruby 2.1, <code>binding.local_variable_set(:foo, 1)</code> are all equivalent to:</p>
  
  <pre><code>1.times do
    foo = 1
  end
  </code></pre>
  
  <p>in other words, they set <code>foo</code> in the context of a <em>new</em> local context, such that the value is inaccessible outside of that context.</p>
  
  <p>Is what I'm looking to do possible?</p>
  
  <p>Update: This question is not specific to any particular local variable context (module/class, method, proc, block, etc.). I'd be interested in knowing definitively any context where it can or cannot be done.</p>