Going through some legacy Ruby code that I'm updating for a client, I came across a seemingly random problem where some elements of an array weren't being removed properly. Here's a simplified version. Can you see the problem?
@example_array = ["a","b","c","d","e","f"] @example_array.each do |example_element| @example_array.delete(example_element) end
The element after each element that got deleted successfully doesn't get deleted. Why? The delete call re-indexes the array in place before the iterator comes around again. The same is true, incidentally, of the insert method, which in the same context could continue infinitely.
Moral of the story: don't mess with the number of items in an enumerable as you're iterating through it. If you need this functionality, maybe just make a copy and modify that:
@example_array = ["a","b","c","d","e","f"] @example_array_copy = @example_array.dup @example_array.each do |example_element| @example_array_copy.delete(example_element) end @example_array = @example_array_copy





Post a Comment