Forum: Ruby Loops and Iterators Difference

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8106f37727c11d8c293326a06a1c1ffa?d=identicon&s=25 Soh Dubom (sohdubom)
on 2008-10-30 19:30
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.
40613e55d7082e5f08429dfb50d0680e?d=identicon&s=25 Stefan Lang (Guest)
on 2008-10-30 21:10
(Received via mailing list)
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
8106f37727c11d8c293326a06a1c1ffa?d=identicon&s=25 Soh Dubom (sohdubom)
on 2008-10-31 11:32
Thanks Stefan ... very good explanation :-)
This topic is locked and can not be replied to.