O'Reilly logo

The Ruby Programming Language by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required