concept collection in category ruby

appears as: collection, collections, collection
The Well-Grounded Rubyist, Third Edition

This is an excerpt from Manning's book The Well-Grounded Rubyist, Third Edition.

The main programming logic comes from looping through the list of directory entries (see the sidebar “Using each to loop through a collection”) and from the case statement, a conditional execution structure. You’ll see both of these techniques in detail in chapter 6.

Using each to loop through a collection

The expression Dir["/tmp/*"].each do |f| is a call to the each method of the array of directory entry names. The entire block of code starting with do and ending with end (the end that lines up with Dir in the indentation) gets executed once for each item in the array. Each time through, the current item is bound to the parameter f; that’s the significance of the |f| part. You’ll see each several times in the coming chapters, and we’ll examine it in detail when we look at iterators (methods that automatically traverse collections) in chapter 9.

Also, keep in mind that collections are, themselves, objects. You send them messages, assign them to variables, and so forth, in normal object fashion. They just have an extra dimension, beyond the scalar.

Here, as with arrays, strings, and other objects, << connotes appending to a collection or mutable object. If you try to add an object that’s already in the set (or an object that’s content-equal to one that’s in the set), nothing happens: