title: Copying objects in an array before removing it
body: <p>The code below loops through an array <code>factor_list</code> and checks if each of them contains a specified variable. If so, remove them from the array, multiply them together, and sum out the final result with respect to the variable. After all the operations, add the factor back to the array.</p>
  
  <pre><code>temp_factor = nil
  factor_list.each{|factor|
          if factor._variables.include?(variable)
              if temp_factor == nil
                  temp_factor = factor
              else
                  temp_factor = multiply(temp_factor, factor)
              end
              factor_list.delete(factor)
          end
      }
  temp_factor = sumOut(temp_factor, variable)
  factor_list &lt;&lt; temp_factor
  </code></pre>
  
  <p>The problem is, <code>temp_factor</code> is always <code>nil</code> in every iteration, even if it has been set in a previous loop. I thought the main problem was because of the deletion in the array, so I removed the deletion for testing, and that solved the problem (but my array is full of trash of course). So I came to the conclusion that my <code>temp_factor</code> was a shallow copy of the object, and so its referencing object is gone with the original one. I then tried doing a deep copy using the marshal trick, but it didn't help.</p>
  
  <p>That was all I have got, as I was unable to solve the problem. Can anyone help me identify the mechanism behind all these myths?</p>
  
  <p>It's cool that you guys give very nice advice about rewriting the code to avoid problems, and they really help! But I'm still wondering what caused the above problem? It would be nice if I can learn that bit of information!</p>