In Ruby, iterators are methods supported by Arrays and Hashes. These two classes are Ruby’s tools for dealing with collections, and iterators return elements within a collection, one-by-one. There are two main methods to return elements out of an array or hash.
.each method can be called when you want to list your collections one element at a time.
Lets first confirm that we can actually use the
.each method on an array. We can do something like so for confirmation:
We have confirmed that
.each is an available method in this Array object with the first line. We can also generate a complete list of methods available by just appending the
.methods method to the object in question. That is the line starting with
 pry(main)> in the illustration above.
Lets see a quick demonstration of how we could use the
.each method in practice:
Above we assigned an array to the
color_list variable. The array contains seven elements initially, and we iterate over the array using the
.each method to select all of the elements larger than 4 letters and place them inside of a different array called
If we wanted to iterate over the array’s index instead of it’s elements, we could utilize the
.each_index method like so:
.each_index does exactly the same thing as the
.each method does, except that instead of listing the elements contained inside the array, it lists the indexes.
.map (which are synonymous) creates a new array containing the values returned to it by the block.
Here is an example:
.collect! we can temporarily or permanently modify the elements in our array with statements written inside a code block.