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 ...
Get The Ruby Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.