0

Sometimes I need to preserve the original value of a variable, do stuff and then restore its original value kind of like this:

def method
  original_value = @variable
  @variable = true

  result = # Do stuff

  @variable = original_value
  result
end

Is there some kind of language construct in Ruby which would allow me to do it simpler?

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:

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

Is there a better alternative for achieving this?

e.nikolov
  • 127
  • 1
  • 11
  • 4
    This seems like a workaround for a design problem; I really don't like the idea at all. It means that code that modifies the variable in question now has two contexts, one of which is invisible when you're looking at the modifying code (unless it's local to the block, in which case you don't need an instance variable). While I don't know your usecase this seems like a heavy, confusing hammer for what seems like a screw. – Dave Newton Apr 23 '15 at 17:59
  • Can you assign the value of the variable to another variable (or clone it if the value is a mutable object) in the inner method? I don't think there's a built-in ruby construct for doing this, though you could certainly write your own generalized one. I'd do it more like your first approach though, and avoid the eval call. You might find [instance_variable_get and instance_variable_set](http://ruby-doc.org/core-1.9.3/Object.html#method-i-instance_variable_get) handy. – alexcavalli Apr 23 '15 at 18:11

0 Answers0