Hi –
On Sat, 4 Sep 2010, Christopher D. wrote:
unexpected results.
represents. This isn’t like any other Enumerable in core Ruby.
I’d say that the enumerator represents enumeration logic (i.e., the
logic borrowed from its “host” method), rather than a particular
sequence. So you get the following parallels:
ruby-1.9.1-p378 > a = [1,2,3,4]
=> [1, 2, 3, 4]
ruby-1.9.1-p378 > e = a.each_with_index
=> #Enumerator:0x0000000af4dcb0
ruby-1.9.1-p378 > a.each_with_index.to_a
=> [[1, 0], [2, 1], [3, 2], [4, 3]]
ruby-1.9.1-p378 > e.to_a
=> [[1, 0], [2, 1], [3, 2], [4, 3]]
ruby-1.9.1-p378 > a.each_with_index.each
=> #Enumerator:0x0000000af0eb28
ruby-1.9.1-p378 > e.each
=> #Enumerator:0x0000000af4dcb0 # returns itself, since it’s
# already an enumerator
ruby-1.9.1-p378 > a.each_with_index.each {}
=> [1, 2, 3, 4]
ruby-1.9.1-p378 > e.each {}
=> [1, 2, 3, 4]
In other words, the enumerator is behaving like a.each_with_index, not
like a and not like itself.to_a. This isn’t surprising, of course, since
e is the return value from a.each_with_index And I think it’s
consistent. In particular, note the last pair of examples, which both
return the original array object.
I guess I’m not sure how else it could work, since anything else would
(I think) be a departure from the idea that the enumerator gets its each
logic not just from a particular object but from an object/method
combination.
David
–
David A. Black, Senior Developer, Cyrus Innovation Inc.
The Ruby training with Black/Brown/McAnally
Compleat Philadelphia, PA, October 1-2, 2010
Rubyist http://www.compleatrubyist.com