Reputation: 296
Assume we have
hash = { a: 1, b: 2 }
hash2 = hash.to_hash
when I change value in hash2 it affect value in hash
hash2[:a] = 5
# hash[:a] = 5
Why ruby acts like that ? How to fix this ?
Upvotes: 0
Views: 100
Reputation: 164809
Calling to_hash
on a Hash returns itself. hash
and hash2
are the same object.
2.6.5 :001 > hash = { a: 1, b: 2 }
=> {:a=>1, :b=>2}
2.6.5 :002 > hash2 = hash.to_hash
=> {:a=>1, :b=>2}
2.6.5 :003 > hash.object_id
=> 70244375263800
2.6.5 :004 > hash2.object_id
=> 70244375263800
Upvotes: 2