Hi --

On Sun, 22 Nov 2009, Omran Nazir wrote:

> Hi, I know this is a very newbie question but its one concept that
> despite google and the O'Riley book I cant get my head around.

It isn't a very nuby question at all. Enumerators are a pretty
advanced topic!

> Can someone please give a simple explantion of what exactly an
> Enumerator is, what it can act on and why you can pass
> 'array.to_enum' to a method that expect 'array'? What sort of
> objects can be defined as 'enumerable' and what makes them so? What
> is the difference between and Enumerator and an Iterator?

An Enumerator is an Enumerable object (it has all the Enumerable
methods, like map, inject, find, etc.). The difference between an
enumerator and most enumerable objects is that most enumerable objects
have a "natural" solution to the question of what items they are
enumerating (or iterating over). For an array, the natural solution is
that the items are the elements of the array. For a hash, it's the
key/value pairs, and so on.

An enumerator knows about the Enumerable methods, but it doesn't have
any natural or automatic sense of what to iterate through. Therefore,
it has to attach itself to another object -- in fact, to a specific
method on another object.

Once you hook an enumerator up to a method on another object, the
enumerator will perform all of its enumerable operations (map, find,
etc.) by drawing on the output from that method.

Here's a kind of artificial example that might show you the basic
workings:

class MyDemo
   def yield_stuff
     yield 1
     yield 22
     yield 333
     yield 4444
   end
end

md = MyDemo.new
e = md.to_enum(:yield_stuff)

p e.select {|x| x > 100 }   # [333, 4444]

If you rename yield_stuff to each, and create the enumerator like
this:

   e = md.to_enum

it will still work, because the default method the enumerator attaches
to is each.

Note that I would be able to pass my enumerator to any method that
expected an enumerable object, on which it could call select and other
enumerable methods.

I don't think I've answered everything but hopefully that will get you
started.


David

-- 
THE COMPLEAT RUBYIST, Ruby training with Black/Brown/McAnally!
January 22-23, Tampa, Florida
Info and registration at http://www.thecompleatrubyist.com
--------------------------------------
My new job: http://tinyurl.com/yfpn9hz