[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Loops and Iterators Difference

Soh Dubom

10/30/2008 6:29:00 PM

Hi. The way I understand, both loops and iterators are, 'loops', but the
sutil difference is that a loop is used to just loop several times and
an iterators loops several times and also access some attribute of the
element being loop.

I'm actually trying to find a better and clear explanation of the
difference between loop and iterator.
--
Posted via http://www.ruby-....

2 Answers

Stefan Lang

10/30/2008 8:09:00 PM

0

2008/10/30 Soh Dubom <sohdubom@yahoo.com>:
> Hi. The way I understand, both loops and iterators are, 'loops', but the
> sutil difference is that a loop is used to just loop several times and
> an iterators loops several times and also access some attribute of the
> element being loop.
>
> I'm actually trying to find a better and clear explanation of the
> difference between loop and iterator.

An iterator is an object that allows us to traverse the
elements of a data structure. In Ruby we usually use
"internal" iterators, that means we don't need to explicitly
manage an iterator object:

my_tree.each_node { |node| node.do_something }

Using an external iterator (in combination with a loop!) could look
like this:

iterator = my_tree.each_node_iterator
while iterator.has_next?
node = iterator.next
node.do_something
end

In both cases, the iterator allows us to traverse the data
structure without knowledge about its internals. Which frees
us to change the implementation later without changing
client code.

A loop simply means repeating a sequence of statements,
endlessly in the simplest case:

loop { do_something }

We could use a loop to traverse a data structure,
say a linked list:

item = people
while item
item.object.do_something
item = item.next
end

But this code breaks when we decide to use e.g. an array
instead of a list to store people.

Stefan

Soh Dubom

10/31/2008 10:32:00 AM

0

Thanks Stefan ... very good explanation :-)
--
Posted via http://www.ruby-....