Skip to content

Instantly share code, notes, and snippets.

@wildmaples
Created December 26, 2022 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wildmaples/07a2a18dbc44ec62851b6837664ded1e to your computer and use it in GitHub Desktop.
Save wildmaples/07a2a18dbc44ec62851b6837664ded1e to your computer and use it in GitHub Desktop.
Ruby's Enumerator in Ruby
class SimpleEnumerator
def initialize(&block)
raise ArgumentError unless block_given?
@block = block
end
def take(num)
@fiber = Fiber.new do
@block.call(EnumYielder.new)
end
ary = []
num.times do
ary << self.next
end
ary
end
private
def next
@fiber.resume
end
end
class EnumYielder
def <<(value)
Fiber.yield(value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment