Question

In this code:

fiber = Fiber.new do |first, second|
  num = Fiber.yield first + second + 2
end

puts fiber.resume 5, 4
puts fiber.resume 3

The output is 11 and 3 each on a separate line.

I understand why the output is 11 for the first fiber.resume (its parameters are passed as block arguments to Fiber.new) but I don't understand why the second fiber.resume returns 3. What's going on?

Was it helpful?

Solution

From documentation:

The Fiber#resume method accepts an arbitrary number of parameters, if it is the first call to resume then they will be passed as block arguments. Otherwise they will be the return value of the call to Fiber.yield

Your second call to resume is only returning the value returned by Fiber#yield, which would be simply 3.

http://www.ruby-doc.org/core-2.0.0/Fiber.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top