title: ruby construct for preserving original value of a variable after block execution
body: <p>Sometimes I need to preserve the original value of a variable, do stuff and then restore its original value kind of like this:</p>
  
  <pre><code>def method
    original_value = @variable
    @variable = true
  
    result = # Do stuff
  
    @variable = original_value
    result
  end
  </code></pre>
  
  <p>Is there some kind of language construct in Ruby which would allow me to do it simpler?</p>
  
  <p>I tried to search for this, but I couldn't really come up with any googleable search terms. I managed to code my own solution for it by passing the current binding and then using eval to preserve the original value in the original context:</p>
  
  <pre><code>def preserve_value(var, bind)
    eval "lksdflkjsdlkfjdslkfjsdlkfj123214343245435324 = #{var}", bind
    result = yield
    eval "#{var} = lksdflkjsdlkfjdslkfjsdlkfj123214343245435324", bind
  
    result
  end
  
  def method
    preserve_value :@variable, binding do
      @variable = 3
      # Do stuff
    end
  end
  </code></pre>
  
  <p>Is there a better alternative for achieving this?</p>