0
0
Rubyprogramming~20 mins

Fiber for cooperative concurrency in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Fiber Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of simple Fiber switch
What is the output of this Ruby code using Fiber for cooperative concurrency?
Ruby
fiber = Fiber.new do
  puts "Step 1"
  Fiber.yield
  puts "Step 2"
end

fiber.resume
puts "Between resumes"
fiber.resume
A
Between resumes
Step 1
Step 2
B
Step 1
Step 2
Between resumes
C
Step 1
Between resumes
D
Step 1
Between resumes
Step 2
Attempts:
2 left
💡 Hint
Remember that Fiber.yield pauses the fiber and returns control to the caller.
🧠 Conceptual
intermediate
1:30remaining
Fiber behavior on resume after completion
What happens if you call resume on a Ruby Fiber that has already finished executing?
AIt raises a FiberError indicating dead fiber
BIt restarts the fiber from the beginning
CIt blocks the current thread until the fiber is ready
DIt silently does nothing and returns nil
Attempts:
2 left
💡 Hint
Think about whether fibers can be restarted once done.
🔧 Debug
advanced
2:00remaining
Identify the error in Fiber usage
What error does this Ruby code produce when run?
Ruby
fiber = Fiber.new do
  Fiber.yield 1
  Fiber.yield 2
end

puts fiber.resume
puts fiber.resume
puts fiber.resume
AFiberError: dead fiber called
BNo error, outputs 1 2 nil
CTypeError: wrong argument type
DLocalJumpError: no block given
Attempts:
2 left
💡 Hint
Check what happens when resume is called after the fiber finishes all yields.
🚀 Application
advanced
2:30remaining
Using Fiber to alternate execution
Given two fibers that print numbers and letters alternately, what is the output of this code?
Ruby
numbers = Fiber.new do
  (1..3).each do |n|
    puts n
    Fiber.yield
  end
end

letters = Fiber.new do
  ['a', 'b', 'c'].each do |l|
    puts l
    Fiber.yield
  end
end

while numbers.alive? || letters.alive?
  numbers.resume if numbers.alive?
  letters.resume if letters.alive?
end
A
a
b
c
1
2
3
B
1
a
2
b
3
c
C
1
2
3
a
b
c
D
a
1
b
2
c
3
Attempts:
2 left
💡 Hint
Fibers yield after printing each item, so they alternate execution.
🧠 Conceptual
expert
2:00remaining
Fiber vs Thread in Ruby concurrency
Which statement best describes the difference between Ruby Fibers and Threads?
AFibers automatically use multiple CPU cores; Threads require manual synchronization
BFibers run in parallel on multiple CPU cores; Threads run only one at a time
CFibers are cooperatively scheduled and run in a single thread; Threads are preemptively scheduled and can run in parallel
DFibers and Threads are identical in scheduling and execution
Attempts:
2 left
💡 Hint
Think about how control switches between fibers and threads.