I’m iterating through a Set and deleting some items, like…
set.each do |e| set.delete e if e % 2 == 0 end
…and I’m having no problem with it; the set stays consistent. I’m just deleting the currently iterated element, not random elements in the set. Is this guaranteed to work, or am I stepping on a minefield and just being lucky?
(I vaguely remember that modifying the currently iterated element was OK, but maybe that was another language.)
I would not recommend on deleting elements in an Enumerable each block, but it depends on the iterator used. I would instead go for reject! and then eachfor the remaining elements.
For this particular example, it seems that both Hash and Set uses the BaseIterator module (defined in hash.cr) and that actually skips deleted entries, so it should be safe. But since every Enumerable class brings their own each method you should not rely on this behavior.