Skip to content

Instantly share code, notes, and snippets.

@wildmaples
Created Dec 26, 2022
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