I have tried to phrase this to the best of my ability. I have a hash that I perform some operations on but before I do this, I store this hash in another variable. Now when I access this variable, the values seem to have changed, how can I go around it. Example:
hash = {a: "1", b: "2", c: "3"}
hash_copy = hash
hash["a"]=4
puts(hash_copy["a"]) #prints 4 instead of 1
How can I get the put statement to print 1 instead of 4, that is, print the original value.
CodePudding user response:
deep_dup
is your friend
hash_copy = hash
is just assigning a pointer not making a copy
so ruby specific options are clone
and deep_copy
In your case copy
will do but both should work fine for you
Ruby clone
hash_copy = hash.clone
Rails, a little buggy in earlier rails versions but is a ruby function and will work for you
hash_copy = hash.deep_dup
is what you need
https://apidock.com/rails/Hash/deep_dup
CodePudding user response:
Use Hash#merge
instead which returns a modified copy of the hash instead:
hash = {a: "1", b: "2", c: "3"}
hash_copy = hash.merge(a: 4)
In general assigning hash keys should only be done to explicitly modify a hash - for everything else there are better methods.