The code below loops through an array factor_list 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.
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 << temp_factor
The problem is, temp_factor is always nil 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 temp_factor 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.
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?
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!
College years with C++ and STL had taught me hard: never ever modify a collection that you’re iterating at the moment. So, instead of deleting items in place, why don’t you try to build a new array?