Skip to content

Chapter 4 of 7

Iterators and Functional Collections

Iteration is at the heart of idiomatic Ruby, and most collection methods are powered by the Enumerable module. The each method is the workhorse of iteration: it walks through a collection and yields each element to a block, returning the original collection unchanged. Methods like map, select, and reduce are layered on top of each, so any class that defines its own each method and includes Enumerable gains a powerful suite of operations.

The map method, also known by its alias collect, applies a block to every element and collects the results into a new array. For example, doubling a list produces [2, 4, 6] from the original [1, 2, 3]. The select method returns a new array containing only the elements for which the block returns a truthy value, making it ideal for filtering. The reduce method, aliased as inject, folds a collection into a single value by repeatedly applying a binary operation, starting from an optional initial accumulator. Combining these methods allows Ruby code to express transformations on data clearly and concisely without explicit loops.

Because Enumerable provides many additional methods such as sort, min, max, and find, defining an each method on a custom class and including Enumerable is the standard way to make that class behave like a first-class collection. This design reflects Ruby's philosophy: rather than building a large inheritance hierarchy of collection types, the language provides a small set of core iteration primitives and composes them into a rich set of higher-level operations.

All chapters
  1. 1Core Data Structures
  2. 2Blocks, Procs, and Lambdas
  3. 3Classes, Inheritance, and Modules
  4. 4Iterators and Functional Collections
  5. 5Exception Handling and File I/O
  6. 6Strings, Patterns, and Operators
  7. 7Metaprogramming and the Ruby Ecosystem

Drill it

Reading is not remembering. These come from the Ruby Programming deck:

Q

What is a Symbol in Ruby?

A Symbol is a lightweight, immutable identifier prefixed with a colon, e.g. :name. Symbols are stored in memory only once, making them more efficient than strin...

Q

How do you create an Array in Ruby?

An Array is an ordered collection created with square brackets or Array.new.Examples:nums = [1, 2, 3]words = %w[hello world]empty = Array.new(5, 0)

Q

How do you create a Hash in Ruby?

A Hash is a collection of key-value pairs.Examples:h = { name: "Alice", age: 30 }h = Hash.new(0)Access values with h[:name].

Q

What is a block in Ruby?

A block is an anonymous chunk of code enclosed in do...end or curly braces { } that can be passed to a method.Example:[1,2,3].each { |n| puts n }