/simple_enumerator.rb Secret
Created
December 26, 2022 13:07
Star
You must be signed in to star a gist
Ruby's Enumerator in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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