JavaScript – Nuances of myArray.forEach vs for loop

The most substantive difference between the for loop and the forEach method is that, with the former, you may break out of the loop. You can simulate continue by simply returning from the function passed to forEach, but there is no way to stop looping altogether. Aside from that, the two accomplish effectively the same … Read more

iterating over each character of a String in ruby 1.8.6 (each_char)

I have the same problem. I usually resort to String#split: “ABCDEFG”.split(“”).each do |i| puts i end I guess you could also implement it yourself like this: class String def each_char self.split(“”).each { |i| yield i } end end Edit: yet another alternative is String#each_byte, available in Ruby 1.8.6, which returns the ASCII value of each … Read more

Why does next raise a ‘StopIteration’, but ‘for’ do a normal return?

The for loop listens for StopIteration explicitly. The purpose of the for statement is to loop over the sequence provided by an iterator and the exception is used to signal that the iterator is now done; for doesn’t catch other exceptions raised by the object being iterated over, just that one. That’s because StopIteration is … Read more

How to find the index of current object in range-based for loop?

Yes you can, it just take some massaging 😉 The trick is to use composition: instead of iterating over the container directly, you “zip” it with an index along the way. Specialized zipper code: template <typename T> struct iterator_extractor { typedef typename T::iterator type; }; template <typename T> struct iterator_extractor<T const> { typedef typename T::const_iterator … Read more

How does RecursiveIteratorIterator work in PHP?

RecursiveIteratorIterator is a concrete Iterator implementing tree traversal. It enables a programmer to traverse a container object that implements the RecursiveIterator interface, see Iterator in Wikipedia for the general principles, types, semantics and patterns of iterators. In difference to IteratorIterator which is a concrete Iterator implementing object traversal in linear order (and by default accepting … Read more

Is it possible to do start iterating from an element other than the first using foreach?

Yes. Do the following: Collection<string> myCollection = new Collection<string>; foreach (string curString in myCollection.Skip(3)) //Dostuff Skip is an IEnumerable function that skips however many you specify starting at the current index. On the other hand, if you wanted to use only the first three you would use .Take: foreach (string curString in myCollection.Take(3)) These can … Read more