Skip to content

Instantly share code, notes, and snippets.

@wildmaples
Created December 26, 2022 13:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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