Bug #12036


Enumerator's automatic rewind behavior

Added by slash_nick (Ryan Hosford) over 8 years ago. Updated almost 5 years ago.

Target version:


When enumerating an enumerator, the enumerator automatically rewinds when #next raises an error. The concern here is that someone may need to handle that error and continue processing the rest of the enumerator.

12:22 < Ox0dea> I think tjohnson found where the StopIteration was being raised?
12:23 < tjohnson> A friend in #projecthydra pointed me here:
12:24 < tjohnson> seems quite deliberate. compare:
12:25 < Ox0dea> Yeah, Line 651 in there is the one birthing the new Fiber, and since dead ones don't maintain context, the surrounding Enumerator can't pick up where it left off.
12:26 < Ox0dea> It's almost certainly intentional, and most likely even The Right Thing, but "make easy things easy and hard things possible".

tjohnson first demonstrated the behavior in a gist:
lucasb also produced a snippet that clearly demonstrates the behavior:

0x0dea, lucasb, tjohnson, rthbound

Updated by kernigh (George Koehler) over 6 years ago

I don't want Ruby to change this behavior. Enumerable#next can't continue the iteration if it raises an exception. That's why it has the automatic rewind behavior.

Here's a quick example. In this script, we handle the oops and expect the last to return 44, but there is automatic rewind so it returns 11.

def peach
  yield 11
  yield 22
  fail 'oops'
  yield 44

e = enum_for(:peach)
puts              #=> 11
puts              #=> 22
( rescue puts $!)  #=> oops
puts              #=> 11

Now we want to change the behavior of Enumerable#next so it would return 44. This seems impossible, because #peach always raises an error and never reaches yield 44. To make this change, we would need to modify Ruby to divert some errors between fibers. When the fiber running #peach tries to raise an error, Ruby would switch to the fiber running Enumerable#next before raising the error. Later, if the program switches back to the fiber of #peach, then #peach would continue as if it had never raised an error. With this change, the caller of #next can rescue the error, and #peach can reach yield 44.

In our modified Ruby, Enumerable#next would divert errors that should never be diverted. The next script might crash our modified Ruby.

def teach
  "str" + 2

e = enum_for(:teach)
( rescue puts $!)
#=> no implicit conversion of Integer into String
#=> crash Ruby???

We rescue a TypeError from String#+, then tell Ruby to continue the iteration. Our modified Ruby wouldn't have automatic rewind, so the fiber running #teach would continue the execution of String#+ as if it never raised TypeError. Then the C code implementing String#+ might use 2 as a String and crash Ruby! This is why I want Ruby to keep automatic rewind.

Actions #2

Updated by jeremyevans0 (Jeremy Evans) almost 5 years ago

  • Status changed from Open to Closed

Also available in: Atom PDF