Loops and Iterators Difference

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.

2008/10/30 Soh D. [email protected]:

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

Thanks Stefan … very good explanation :slight_smile: