title: ruby: can't add a new key into hash during iteration
body: <p>I have three hashes:</p>
  
  <pre><code>db_headers = {"1"=&gt;"first_name", "2"=&gt;"last_name"}
  csv_headers = {"1"=&gt;"First Name", "2"=&gt;"Last Name"}
  csv_records = {"0"=&gt;{"id"=&gt;"11", "first_name"=&gt;"first_0", "Last Name"=&gt;"last_0", "created_at"=&gt;"2014-08-12 17:02:28 UTC", "updated_at"=&gt;"2014-08-12 17:02:28 UTC"}, "1"=&gt;{"id"=&gt;"12", "first_name"=&gt;"first_1", "Last Name"=&gt;"last_1", "created_at"=&gt;"2014-08-12 17:02:28 UTC", "updated_at"=&gt;"2014-08-12 17:02:28 UTC"}}
  </code></pre>
  
  <p>db_headers and csv_headers are matched by their keys. For example, their key "2" values contain "last_name" and "Last Name" respectively. My goal is wherever the values are different between db_headers and csv_headers where the keys are the same, then I need to swap the key in csv_records with value of db_headers. So for example, csv_records key will change from "Last Name" to "last_name", since db_headers and csv_headers value at key "2" were different.</p>
  
  <p>This is what I came up with:</p>
  
  <pre><code>  csv_records.each do |record_key,record_value|
      csv_headers.each do |csv_key,csv_value|
        if record_value.has_key? csv_value
            db_headers.each do |db_key, db_value|
              if csv_key == db_key
                csv_records[db_value] = csv_records.delete csv_value
                break
              end
            end
            break
        end
      end
    end
  </code></pre>
  
  <p>Unfortunately it fails:</p>
  
  <pre><code>RuntimeError: can't add a new key into hash during iteration
      from (irb):12:in `[]='
      from (irb):12:in `block (3 levels) in irb_binding'
      from (irb):10:in `each'
      from (irb):10:in `block (2 levels) in irb_binding'
      from (irb):8:in `each'
      from (irb):8:in `block in irb_binding'
      from (irb):7:in `each'
      from (irb):7
  </code></pre>
  
  <p>This made the error go away:</p>
  
  <pre><code>csv_records.keys.each do |record_key|
      csv_headers.keys.each do |csv_key|
        if csv_records[record_key].has_key? csv_headers[csv_key]
            db_headers.keys.each do |db_key|
              if csv_key == db_key
                csv_records[db_headers[db_key]] = csv_records.delete csv_headers[csv_key]
                # break is needed becasue csv_key wont exist in next iteration
                break
              end
            end
        end
      end
    end
  </code></pre>
  
  <p>But csv_records is supposed to now have a value last_name, but it continues to have "Last Name" instead.</p>