Reputation: 1308
I have a function that generates an enumerator in the following manner:
def create_example_enumerator(starting_value)
current = starting_value
e = Enumerator.new do |y|
loop do
current += 1
y << current
end
end
end
The current behavior is pretty straightforward.
> e = create_example_enumerator(0)
#<Enumerator: details>
> e.next
1
> e.next
2
> e.rewind
#<Enumerator: details>
> e.next
3
I would like e.rewind
to reset the enumerator back to it's starting value.
Is there a nice way to do that while still using an infinite enumerator?
Upvotes: 4
Views: 295
Reputation: 11904
This should work:
n = Enumerator.new do |y|
number = 1
loop do
y.yield number
number += 1
end
end
n.next #=> 1
n.next #=> 2
n.next #=> 3
n.rewind
n.next #=> 1
Upvotes: 5