Iterating a block in Ruby is simple enough - it finishes cleanly and proceeds on to the rest of the code.
Iterating with an Enumerator, on the other hand, is a bit more confusing. If you call :each without a block, an Enumerator is returned instead. :next can then be called on the Enumerator to get each next iterative value.
And then the odd part- when iteration is complete, instead of the Enumerator returning nil, it throws an exception: "iteration reached at end". The result is that it doesn't even return a value.
For instance:
test = [ 'test_value' ]
enumerator = test.each
enumerator.next
>> "test_value"
enumerator.next
>> StopIteration: iteration reached at end
Is the reason for this simply so that nil values can be returned by the Enumerator? The answer occurs to me only as I post this (so I am going to post it still), but seems like it must be the case.
If that is so, is this a typical way of handling such issues? It seems odd to use an Exception to handle code that essentially performs as expected.
#loop
catches this exception, soloop { enumerator.next }
eliminates the need to explicitly handle it. – Vasya