One of the patterns described in the Design Patterns book is the Iterator pattern. Iterators are objects that can loop over elements of a collection one at a time. There are two kinds of iterator. External iterators are ones where the actual looping code is in the client application. The iterator provides methods to return the next object and to test if you're at the end. Internal iterators are ones where the actual looping code is in the iterator. The client passes in a block closure or a callback method name for the iterator to use on each element.
Iterators work well in general but there are times when they can produce unexpected results. For example, if you delete elements from a collection while iterating over it, you can get incorrect results. My recommendation is to iterate over a shallow copy of the collection if you're planning to make changes to it while you iterate.Download