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?