Chapter 9. Collection and container objects

 

In this chapter

  • Sequentially ordered collections with arrays
  • Keyed collections with hashes
  • Inclusion and membership tests with ranges
  • Unique, unordered collections with sets

In programming generally, you deal not only with individual objects but with collections of objects. You search through collections to find an object that matches certain criteria (like a magazine object containing a particular article); you sort collections for further processing or visual presentation; you filter collections to include or exclude particular items; and so forth. All of these operations, and similar ones, depend on objects being accessible in collections.

Ruby represents collections of objects by putting them inside container objects. In Ruby, two built-in classes dominate the container-object landscape: arrays and hashes. We’ll start this chapter by looking at the Array and Hash classes: first in comparison with each other, to establish an overall understanding, and then separately.

9.1. Arrays and hashes in comparison

9.2. Collection handling with arrays

9.3. Hashes

9.4. Ranges

9.5. Sets

9.6. Exploring the set.rb source code

9.7. Summary