-1

I want to copy one hash to a new hash and use it later. The previous one will change and I do not want to use the changed one.

I have done:

hash_2 = Hash.new()
hash_2 = hash_1.clone

When hash_1 changed, hash_2 is also changed, and I cannot figure out what I am doing wrong.

Ectoras
  • 1,297
  • 3
  • 13
  • 33
  • 1
    You're probably not trying to clone an empty hash. Show some code that demonstrates your actual problem, i.e. the *"when hash_1 changed, hash_2 is also changed"* part – Stefan Jul 21 '15 at 12:21
  • After your edit, it has become unclear what `hash_1` is. Also, your first line in the code became redundant. – sawa Jul 21 '15 at 12:29
  • ok, let me explain, hash_1 is the one which contains elements, and hash_2 is an empty one. I want to copy hash_1 to hash_2 – Ectoras Jul 21 '15 at 12:33

1 Answers1

2

You can use 'Marshal' to deep copy.

h1 = {:key_1 => {:sub_1 => "sub_1", :sub_2 => "sub_2"}}

h2 = Marshal.load(Marshal.dump(h1))

h2[:key_1][:sub_1] = "SUB_1"
h2[:key_1].delete(:sub_2)

p h1
# => {:key_1=>{:sub_1=>"sub_1", :sub_2=>"sub_2"}}
p h2
# => {:key_1=>{:sub_1=>"SUB_1"}}
Lukas Baliak
  • 2,849
  • 2
  • 23
  • 26