title: ruby hashes, why is the value getting overridden
body: <p>Consider the following code snippet: </p>
  
  <pre><code>inner_hash =Hash.new
   trial_hash = Hash.new
  inner_hash.merge!("i_key1"=&gt;"value1")
  inner_hash.merge!("i_key2"=&gt;"value2")
  puts "inner_hash #{inner_hash}"
  trial_hash.merge!("o_key1"=&gt;inner_hash)
  puts "trial_hash #{trial_hash}"
  inner_hash.clear
  inner_hash.merge!("i_key1"=&gt;"value3")
  inner_hash.merge!("i_key2"=&gt;"value4")
  puts "inner_hash #{inner_hash}"
  trial_hash.merge!("o_key2"=&gt;inner_hash)
  puts "trial_hash #{trial_hash}"
  </code></pre>
  
  <p>This is what it prints:</p>
  
  <pre><code>inner_hash {"i_key1"=&gt;"value1", "i_key2"=&gt;"value2"}
  trial_hash {"o_key1"=&gt;{"i_key1"=&gt;"value1", "i_key2"=&gt;"value2"}}
  inner_hash {"i_key1"=&gt;"value3", "i_key2"=&gt;"value4"}
  trial_hash {"o_key1"=&gt;{"i_key1"=&gt;"value3", "i_key2"=&gt;"value4"}, "o_key2"=&gt;{"i_key1"=&gt;"value3", "i_key2"=&gt;"value4"}}
  </code></pre>
  
  <p>Especially see the trial_hash printed in the last line. The value of key "o_key1" is a hash whose value should have been value1 and value2 but have been overwritten to value3 and value4. ideally the expected output should have been:</p>
  
  <pre><code>inner_hash {"i_key1"=&gt;"value1", "i_key2"=&gt;"value2"}
  trial_hash {"o_key1"=&gt;{"i_key1"=&gt;"value1", "i_key2"=&gt;"value2"}}
  inner_hash {"i_key1"=&gt;"value3", "i_key2"=&gt;"value4"}
  trial_hash {"o_key1"=&gt;{"i_key1"=&gt;"value1", "i_key2"=&gt;"value2"}, "o_key2"=&gt;{"i_key1"=&gt;"value3", "i_key2"=&gt;"value4"}}
  </code></pre>
  
  <p>Why is this behaviour observed. What wrong am I doing. Originally the question is very broad and uses loops, which for sample purpose here, i have removed and re-written some of the lines. Any help is greatly appreciated. Thanks</p>
  
  <p><strong>EDIT</strong>: The problem is solved when I replaced inner_hash.clear with inner_hash={}</p>