Iterators and Loops and Enumerables....Oh My!
What is an Iterator?
iterator
An object or routine for accessing items from a list, array or stream one at a time. By extension, the term can be used for an object or routine for accessing items from any data structure that can be viewed as a list. For example, a traverser is an iterator for tree-shaped datastructures.
In ruby that simply means an interator is a method that allows traversal over a collection of objects.
What is an Array?
an Array is an indexed collection of objects. Arrays can hold Strings, Fixnums, intergers. even other arrays
Let's say we have a bunch of twitter user handles in an array like such
and we want to print out all the URLS of all our twitter friends
Twitter has 200 million users. Are you going to sit and write the same code over and over again?
What are Loops?
A loop is a sequence of instruction that is continually repeated until a condition is reached
Loops help you iterate over a collection objects. In this case, It's our list of twitter handels regardless the size of the array
What are Enumerables?
a class with useful functions for traversing searching and sorting over a collection, like:
next
map
inject
to use Enumerable each implement the each method
Block
or.....
or....
For loop
Our each enumerable each and our for loop do exactly the same thing however, let's dig into our enumerable a little more.
each
a method belonging to an Array and other collection classes. It's also an iterator as you can see above. It cycles through the code block that acts on each element in the collection
do
is a ruby key word that signifies the beginning of a block of code
|handle|
the variable name "handle" is the argument passed into our block. in the case of each, the single argument refers to the element in the current iteration
end
closes the block of code used by the each method
Beware of scope
if you try to call the variable url on line 27 you will get a name error: undefined local variable
What is scope ?
The scope of a variable describes where in a program's text the variable may be used, while the extent (or lifetime) describes when in a program's execution a variable has a (meaningful) value. The scope of a variable is actually a property of the name of the variable, and the extent is a property of the variable itself.
A variable name's scope affects its extent.
In our case the variable url only exists in the inner workings of that method. To call that url and have it output something meaningful, it's value would have to be either returned by the method that its contained by or the variable would have to b e defined out side of the inner workings of the method.









