Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active January 4, 2023 23:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save havenwood/113c61b9540728d4932f to your computer and use it in GitHub Desktop.
Save havenwood/113c61b9540728d4932f to your computer and use it in GitHub Desktop.
Fiber FizzBuzz and Fibonacci (silly examples)
require 'fiber'
@dispatcher = Fiber.new do
loop do
[@a, @b].sample.transfer rand 1..100
end
end
@a = Fiber.new do |work|
loop do
sleep 3
@dispatcher.transfer puts "worker a finished unit #{work} ..."
end
end
@b = Fiber.new do |work|
loop do
sleep 3
@dispatcher.transfer puts "worker b finished unit #{work} ..."
end
end
@dispatcher.resume
require 'fiber'
@pool = []
1.upto 100 do |n|
@pool << Fiber.new do
if n % 15 == 0
Fiber.yield 'FizzBuzz'
elsif n % 3 == 0
Fiber.yield 'Fizz'
elsif n % 5 == 0
Fiber.yield 'Buzz'
else
Fiber.yield n
end
end
end
@pool.each { |fiber| puts fiber.resume }
require 'fiber'
class Holidays
attr_reader :halloween, :thanksgiving, :christmas
def initialize
@halloween = Fiber.new do
@thanksgiving.transfer puts 'Trick or treat!'
loop { Fiber.yield puts 'No more candy this season...' }
end
@thanksgiving = Fiber.new do
@christmas.transfer puts 'Gobble, gobble!'
loop { Fiber.yield puts 'The turkeys have gone into hiding...' }
end
@christmas = Fiber.new do
Fiber.yield puts 'Ho, ho, ho!'
loop { Fiber.yield puts 'The presents have all been opened...' }
end
end
end
season = Holidays.new
season.halloween.transfer
season.halloween.transfer
season.thanksgiving.transfer
season.christmas.transfer
require 'fiber'
fibonacci_fiber = Fiber.new do
x, y = 0, 1
loop do
Fiber.yield x
x, y = y, x + y
end
end
10.times.map { fibonacci_fiber.resume }
#=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
fibonacci_fiber.alive?
#=> true
fibonacci_fiber.resume
#=> 55
@aruprakshit
Copy link

Please don't delete it.. Its useful.. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment