Question:
I wrote a simple ruby fiber program to see how they work and got an unexpected result.Note: ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]
Answer:
From the docs,Upon yielding or termination the Fiber returns the value of the last executed expression
In addition to
Fiber.yield
calls, a fiber (like an ordinary function) returns the result of the final expression in the fiber.The body of your fiber is this.
.each
, you yield each line of the file, which gets printed out as you’ve already observed. But then, when the fiber is done, it yields a final value, which is the result of File.open
. And File.open
returns the File
object itself. So your sg.resume
actually sees six results, not five.File#close
or by passing a block to File::open
. In order to be completely safe, your fiber code should probably look like this.If you have better answer, please add a comment about this, thank you!