-
-
Save wildmaples/07a2a18dbc44ec62851b6837664ded1e to your computer and use it in GitHub Desktop.
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