I have a tree that I'm trying to traverse. As I traverse it, I keep a stack of enumerators in which each enumerator is used to enumerate over a tree's children.
I'd like to be able to duplicate this stack of enumerators and hand it to another object so it may traverse the tree starting in the place indicated by the state of the stack.
When I attempt to call #dup on Enumerator, I get an error. Is it possible to duplicate an Enumerator? If not, how could I accomplish the same thing? (I've considered a stack of integers as indices, but am worried about the efficiency.
Here's some code to show what I'm seeing...
Once the first enumerator has started, you cannot duplicate it. That 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
@dup
? You mean calldup
? – Sennacherib#next
is not preferred way to use enumerators in ruby. I believe it is defined using fibers, and stackframes cannot be duplicated. Can you elaborate what do you need this for? Maybe we could suggest more ruby-way of solving your problem. – Nixie#next
is provided by standard ruby libraries, as there are tasks quite hard to solve in functional approach, but it is not preferred way to use them. Enumerators are internally built around#each
method, and this is correct way to use them. – Nixie#zip
method from Enumerable module I haven't found single case in which I could use external enumeration. Anyway -- I believe that we agree with each other deep inside :) It is just matter of single sentence ripped out of context: "#next is not preferred way to iterate in ruby". – Nixie