Rewind an infinite enumerator

I have a function that generates an enumerator as follows:

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 simple.

 > 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 this initial value. Is there a good way to do this while continuing to use an infinite enumerator?

+4
source share
1 answer

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 
+5
source

Source: https://habr.com/ru/post/1444204/


All Articles