This chapter introduces Ruby’s main container objects and explains why collections matter in everyday programming: they let you organize data for searching, sorting, filtering, and retrieval. Ruby’s built-in collection types are treated as ordinary objects, but they add structure for holding many values at once. The chapter also sets up an important idea for later chapters: most collection behavior in Ruby is enhanced through the Enumerable module, while this chapter focuses on the core features of the major collection classes themselves.
Arrays and hashes form the foundation of Ruby collections. Arrays store ordered elements at zero-based integer positions, and the chapter walks through several ways to create them, access and modify elements, combine arrays, transform them, and query their state. Hashes store key/value pairs, with unique keys and insertion order preserved, making them ideal for lookup-driven data. The chapter emphasizes how arrays and hashes overlap and differ, including automatic and explicit conversions between them, nested structures, and Ruby’s support for named arguments that use hash-like syntax.
The chapter then broadens to ranges and sets. Ranges are shown as objects that support inclusion checks and, when finite, enumeration; the discussion highlights the difference between inclusive and exclusive ranges and how methods like cover? and include? can behave differently. Sets are presented as unique, unordered collections useful for membership and set algebra, including union, intersection, difference, and subset/superset tests. Across all of these types, the chapter repeatedly returns to the same themes: object identity, mutability, default behaviors, and the practical consequences of choosing one collection form over another.
```
Summary
Array and Hash are Ruby’s major core container classes.
Ranges principally operate as inclusion test criteria but know how to behave as collections when their makeup permits them to.
Sets are defined in the standard library and add another important tool to Ruby’s collection toolset.
Named arguments prevent you from having to use hash keys as pseudo-keywords and “unpacking” argument hashes in your methods.
The concept of the collection in Ruby is closely associated with the Enumerable module and its principle of dependence on an each method.
FAQ
What is the main difference between arrays and hashes in Ruby?Arrays store objects in an ordered sequence and are accessed by numeric indexes, while hashes store key/value pairs and are accessed by keys. Both preserve insertion order in Ruby, but hashes use programmer-defined keys rather than consecutive integers.How can you create a new array in Ruby?You can create arrays with Array.new, the literal [] constructor, the top-level Array method, or the %w/%i shortcut notations for strings and symbols.Why can Array.new(3, "abc") be risky?Because all three array slots refer to the same string object. Mutating one element can affect the others. If you need separate objects, use a block like Array.new(3) { "abc" }.What does the Array method do when given an object?Array(obj) tries to_ary first, then to_a. If neither exists, it wraps the object in a one-element array.How do you retrieve and replace multiple array elements at once?You can use [] or []= with an index and length, or with a range. For example, a[3,2] retrieves two elements starting at index 3, and a[3,2] = "green", "blue" replaces them.What is the difference between concat and + for arrays?concat modifies the receiver in place, while + returns a new combined array and leaves the original unchanged.How does Ruby handle default values for missing hash keys?If you create a hash with Hash.new, missing keys return nil by default. You can supply a default value, or a block that computes a value each time a missing key is accessed.What is the difference between fetch and [] on a hash?[] returns nil or a default for missing keys, while fetch raises an error unless you provide a fallback value or block.What is the difference between cover? and include? for ranges?cover? checks whether a value lies between the range endpoints by comparison, while include? treats the range more like a collection of discrete values. They can return different results for strings and other non-numeric ranges.What makes a Ruby Set different from an array?A set stores unique elements only, with no duplicates. It supports set operations like union, intersection, and difference, and it is best used when membership and uniqueness matter more than order or indexing.
pro $24.99 per month
access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!