Bird
0
0

What will be printed by this Ruby code involving two Fibers exchanging values?

hard📝 Application Q9 of 15
Ruby - Concurrent Programming
What will be printed by this Ruby code involving two Fibers exchanging values?
fiber_a = Fiber.new do
  val = Fiber.yield 10
  puts "Fiber A got: #{val}"
end

fiber_b = Fiber.new do
  x = fiber_a.resume
  Fiber.yield x + 5
  fiber_a.resume 20
end

puts fiber_b.resume
puts fiber_b.resume
AFiber A got: 20 10 15
B10 Fiber A got: 20 15
C10 15 Fiber A got: 20
D15 10 Fiber A got: 20
Step-by-Step Solution
Solution:
  1. Step 1: First resume fiber_b

    fiber_b resumes fiber_a, which yields 10, so fiber_b.resume returns 10.
  2. Step 2: fiber_b yields 10 + 5 = 15

    Second resume of fiber_b returns 15.
  3. Step 3: fiber_b resumes fiber_a with 20

    fiber_a receives 20 and prints "Fiber A got: 20".
  4. Final Answer:

    10 15 Fiber A got: 20 -> Option C
  5. Quick Check:

    Track yields and resumes carefully [OK]
Quick Trick: Follow resume and yield values step-by-step [OK]
Common Mistakes:
  • Mixing order of printed values
  • Forgetting that Fiber.yield returns control to caller

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes