Hi --
Hello Hal
Generators "externalize" iteration, whereas Enumerator "internalize"
it (but this docs may have already told you).
Generators can be used to create a "controlled stream" of objects,
that you can operate as you where using a remove control: go to the
next (Generator#next), give me the position (Generator#pos), return to
the beginning (Generator#rewind), ...
Enumerators have #next and #rewind too, though (though not #pos). In
1.9, as far as I can tell, the generator.rb library has been removed,
and Generator is now a class inside Enumerator. An Enumerator::Generator
is created automatically, for the use of the enumerator, if you create
an enumerator with a block. Also, these Generators don't have #next and
friends; that's available via the enumerator. (I'm not sure what
happened to #pos.)
As I understand it, the main thing about generators is that "controlled
stream" thing, where you can roll your own sense of iteration, rather
than just piggy-backing on what some enumerable object with its own
ideas about iteration thinks. Here's a (very contrived) 1.9 example:
[dblack@ruby-versions ~]$ cat e.rb message = nil
g = Enumerator::Generator.new do |yielder|
yielder << "Hi."
puts "I've been told to #{message}."
case message
when "leave"
yielder << "Bye."
when "stay"
yielder << "I'm still here!"
end
end
e = Enumerator.new(g)
puts e.next
message = "stay"
puts e.next
e.rewind
puts e.next
message = "leave"
puts e.next
[dblack@ruby-versions ~]$ ruby e.rb Hi.
I've been told to stay.
I'm still here!
Hi.
I've been told to leave.
Bye.
David
···
On Thu, 22 Jul 2010, Ricardo Panaggio wrote:
--
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