Search⌘ K

... continued

Explore how to use Ruby fibers for efficient asynchronous programming. Learn to pass and return values from fibers, generate infinite sequences, and manage control transfer between fibers, including handling common errors like double resume. This lesson enhances your ability to optimize resource management and concurrency in Ruby applications.

We'll cover the following...

Passing and Returning from Fibers

We can pass and return values from fibers. Consider the snippet below:

Ruby
fib = Fiber.new do |firstMsg|
start = 0
puts firstMsg
while true do
newMsg = Fiber.yield start
puts newMsg
start += 1
end
end
10.times do |i|
puts fib.resume("hello #{i}")
sleep(1)
end

The interesting line in the above snippet is:

    newMsg = Fiber.yield start

The above statement can be conceptually broken down as the ordered sequence of the following operations:

  1. Returns the start ...