Cover by David Flanagan, Yukihiro Matsumoto

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Collections

This section documents Ruby’s collection classes. A collection is any class that represents a collection of values. Array and Hash are the key collection classes in Ruby, and the standard library adds a Set class. Each of these collection classes mixes in the Enumerable module, which means that Enumerable methods are universal collection methods.

Enumerable Objects

The Enumerable module is a mixin that implements a number of useful methods on top of the each iterator. The Array, Hash, and Set classes described below all include Enumerable and therefore implement all of the methods described here. Range and IO are other noteworthy enumerable classes. Enumerable was covered briefly in Enumerable Objects. This section provides more detailed coverage.

Note that some enumerable classes have a natural enumeration order that their each method follows. Arrays, for example, enumerate their elements in order of increasing array index. Range enumerates in ascending order. And IO objects enumerate lines of text in the order in which they are read from the underlying file or socket. In Ruby 1.9, Hash and Set (which is based on Hash) enumerate their elements in the order in which they were inserted. Prior to Ruby 1.9, however, these classes enumerate their elements in what is essentially an arbitrary order.

Many Enumerable methods return a processed version of the enumerable collection or a selected subcollection of its elements. Usually, if an Enumerable method returns a collection (rather ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required