Hello,
an enumerator (I hope you didn’t mix enumerator and enumeration up; if
you did, I may just have confused you more.. Sorry if that’s the case),
or iterator, is an object to traverse a collection. In ruby, you usually
get an enumerator by calling one of enumerable’s methods without a
block. This enumerator itself provides all methods of enumerable, as
well as some other nice functionality. It’s just another way to go
through a collection.
An example (taken from the documentation of enumerator1):
%w[foo bar baz].map.with_index { |w, i| “#{i}: #{w}” }
=> [“0: foo”, “1: bar”, “2: baz”]
Since there is no map_with_index function in Enumerable (or Array), we
can’t write that example as concise without an enumerator. We could,
however, do this by hand:
a =
%w[foo bar baz].each_with_index { |w, i| a << “#{i}: #{w}” }
a is now [“0: foo”, “1: bar”, “2: baz”]
To wrap all that up:
-Collection: A collection of things, can be an array, a hash, a linked
list, a mathematical set, … (this is a general concept implemented at
various places in ruby)
-Enumeration: A list of all elements in a collection. Sometimes a
collection itself is an enumeration, sometimes not (this is also a
general concept)
-Enumerable: A module providing a huge functionality for traversing and
manipulating collections (this is a ruby-specific thing)
-Enumerator / Iterator: An object to traverse a collection (this is a
general concept and implemented in ruby)
I hope I could help. ![]()
Regards,
Calvin
On 02.02.2013 06:07, Arup R. wrote:
@calvin - Your example is good. But in this context with this example
how array is differing from enumerator? Thanks