0

Basically, I want to have an old instance of the variable after updating a variable

Here is some example that might explain better:

variable = { a: "#fff" }
saved = variable
variable[:a] = "#000"

saved[:a]

The goal is to get "#fff". Instead last line returns "#000" which is expected. I tried freezing an object:

variable = { a: "#fff" }
saved = variable
saved.freeze
variable[:a] = "#000"

But that will just raise an FrozenError: can't modify frozen Hash error

sheff3rd
  • 63
  • 7

2 Answers2

1

Just duplicate variable

saved = variable.dup
andriy-baran
  • 620
  • 4
  • 16
  • That kinda works but it removes the ids from the variable in case of RoR model. And I want to keep associations too – sheff3rd Apr 10 '18 at 09:48
  • In rails you can use `clone` Take a look at https://stackoverflow.com/a/24650062/2645167 – andriy-baran Apr 10 '18 at 09:50
  • Thanks, that did help! ;) – sheff3rd Apr 10 '18 at 09:53
  • @Sheff3rd you did not mention ActiveRecord, maybe you should clarify your question. – Stefan Apr 10 '18 at 10:14
  • 1
    "Just duplicate variable" – This will not duplicate the variable, it will duplicate the object. It's not helpful to use such imprecise terminology when the reason for the OP's question in the first place was that the OP doesn't fully understand the difference between variables and objects. – Jörg W Mittag Apr 10 '18 at 10:48
0

Just duplicate it:

variable = { a: "#fff" }
saved = variable.dup # attention here
variable[:a] = "#000"

saved[:a]
Alex Antonov
  • 14,134
  • 7
  • 65
  • 142