Clone an enumerator in Ruby?

I have a tree that I am trying to go through. When I cross it, I save an enumeration stack in which each enumerator is used to enumerate over the children of the tree.

I would like to be able to duplicate this stack of enums and pass it to another object so that it can traverse the tree starting at the location indicated by the state of the stack.

When I try to call #dup on an Enumerator, I get an error. Can I duplicate a counter? If not, how could I do the same? (I considered the stack of integers as indices, but I'm worried about efficiency.

Here is some code to show what I see ...

Once the first counter is running, you cannot duplicate it. This is my situation.

a = [1,2,3].each => #<Enumerator: [1, 2, 3]:each> a.next => 1 b = a.dup TypeError: can't copy execution context from (irb):3:in `initialize_copy' from (irb):3:in `initialize_dup' from (irb):3:in `dup' from (irb):3 
+6
source share
2 answers

Deploy your own enumerator class.

Not too much magic for the counter without increasing the internal counter.

 class MyArrayEnumerator def initialize(array) @ary,@n=array,0 end def next raise StopIteration if @n == @ary.length a=@ary [@n];@n+=1;a end end class Array def my_each MyArrayEnumerator.new(self) end end a = [1,2,3].my_each # => #<MyArrayEnumerator:0x101c96588 @n=0, @array=[1, 2, 3]> a.next # => 1 b = a.dup # => #<MyArrayEnumerator:0x101c95ae8 @n=1, @array=[1, 2, 3]> a.next # => 2 b.next # => 2 
+1
source

Use clone instead:

 e1 = [1,2,3].each e1.dup # TypeError: can't copy execution context e2 = e1.clone e1.next #=> 1 e2.next #=> 1 
+1
source

All Articles