What is a Collection anyway?
Ruby provides two basic data structures to help you manipulate collections of objects: the Array and the Hash. These structures are the building blocks with which you can construct even advanced collections with custom behaviour. In this chapter, you will learn how to build custom Ruby collections, inspired from the simplest collection of all: the Array.
Before we delve into the matter, let us review how an Array works. Put simply, a Ruby Array is a collection of objects.
In Ruby, the standard operation all collections perform is the retrieval of elements from the collection sequentially using the each
method. We have already seen how you can use each
on an Array in The RubyMonk Primer on Arrays.
each
accepts a block of code as an argument. It iterates through all elements of the collection and for every element, executes the code.
An example:
Here, the each
method accepts as a parameter a block of code that puts
the number. Since there are three numbers in the list, each
will execute the same block of code thrice, but passes successive numbers to the block for each execution.