Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 134 ยท Collections

The Enumerable Module

Learn Ruby's Enumerable module - the dozens of methods you get by defining each, building your own collection classes, to_enum, lazy evaluation, and Enumerable versus Comparable.

Arrays, hashes, ranges, sets and even files all answer to map, select, sort_by, reduce, min_by and dozens more. They do not each implement those methods separately. They share one module, Enumerable, and the module needs exactly one thing from its host: an each method that yields the items one at a time. Everything else is built on top of each.

That is more than a curiosity. It means you can give your own class the whole toolbox by writing a four-line each and adding include Enumerable. This lesson shows what Enumerable provides, how to use it in your own classes, how to return enumerators when no block is given, what changes with infinite sources and lazy evaluation, and how Enumerable differs from Comparable.

One method in, forty methods out

Ruby A collection class that includes Enumerable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Playlist never defined map, sort, include? or each_slice. It defined each, and Enumerable did the rest. Notice what each does: it passes the block along to the array's each (&block) and returns self, which is the convention for iterators.

Anatomy of a good each

An each method calls yield for every item. This version doesn't wrap an array at all. It generates items itself:

Ruby each with yield, and generated data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The line return to_enum(:each) unless block_given? is a habit worth forming. When the caller passes no block, you return an Enumerator (an object that remembers "call each on this thing") instead of crashing on yield. That makes each.with_index, each_slice(2) and e.next work. The optional block after to_enum lazily computes the size. See Enumerators and Lazy Enumerators for the details.

If you write def each and call yield without the block_given? guard, then obj.each (no block) raises LocalJumpError: no block given (yield). Enumerable's own methods always give each a block, so the omission only shows when users call each directly.

What Enumerable gives you

The module has more than fifty methods. Here is a map of the ones you will use most, grouped by purpose:

Ruby A tour of Enumerable on a range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Learn these in families rather than one by one:

  • Transform: map, flat_map, filter_map, zip.
  • Filter: select/filter, reject, take_while, drop_while, find, find_all, first, take, drop.
  • Fold into one value: reduce/inject, sum, count, min, max, minmax.
  • Group: group_by, partition, chunk_while, slice_when, each_slice, each_cons, tally, uniq.
  • Ask a question: any?, all?, none?, one?, include? (all accept a pattern, which is compared with ===).
  • Order: sort, sort_by, min_by, max_by.

Prefer sort_by, min_by and max_by over sort, min and max with a block of comparisons. They compute the key once per element and are shorter. The pattern argument form (all?(Integer), any?(/error/), grep(1..5)) is also worth knowing.

Enumerable methods return arrays

Most Enumerable methods build and return a plain Array, whatever type the receiver has. Hash is the notable exception: it defines its own select and reject, so filtering a hash gives a hash back (see Hashes). A Set does not do this, as Sets shows, and custom collections do not either:

Ruby Return types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

If you want a Bag back, build it explicitly (as in the last lines) or add your own select. The anonymous block parameter & in def each(&) is a modern shorthand for forwarding a block, new in Ruby 3.1.

Forgetting each

Enumerable is only a set of recipes. If the class has no each, every method fails when it needs the items:

Ruby Including Enumerable without each (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The run ends with main.rb:5:in 'Enumerable#map': undefined method 'each' for an instance of Broken (NoMethodError). This is the whole contract: provide each, and optionally <=> on the items if you use sort, min or max.

Ruby sort needs comparable items (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The sort_by(&:size) line prints [1, 3], because it sorts on the numbers. The sort line stops the program with comparison of Box with Box failed (ArgumentError): Ruby cannot order two Box objects, since they define no <=>. Teaching the class to compare itself is exactly what Comparable is for.

Infinite and lazy collections

Because Enumerable talks to each one item at a time, each can be endless, as long as you ask for a finite part with first, take, take_while or find:

Ruby An endless collection, and lazy chains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

lazy returns a different enumerator that postpones the work until you ask for a result and that stops as soon as it has enough. Without lazy, fib.select(&:even?) would try to collect every even Fibonacci number, forever. Use laziness for endless sources, huge files read line by line, or long chains where you only need the first few results.

Several things at once: each_entry and multiple values

Some each methods yield more than one value, as Hash#each yields a key and a value. Enumerable packs those into arrays, which is why hash blocks can take |key, value|:

Ruby Yielding several values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

yield :a, 1 hands two values; Enumerable wraps them into [:a, 1] for methods that collect results. This is also how Hash gets to_a, min_by and sort_by for free.

Enumerable versus Comparable

The two modules are often confused because both give you "lots of methods for one method". Compare them:

Enumerable Comparable
You provide each <=>
It is about a collection of things a single thing and its order
You get map, select, sort, reduce, min, first... <, <=, >, >=, ==, between?, clamp
Typical hosts Array, Hash, Range, Set, Struct, File Integer, String, Time, Version, Money

They work together: a collection of comparable things can sort, min and max itself. Enumerable#sort calls <=> on the items. Next, Comparable shows how to give your own objects an order.

Design notes

  • Implement each first, give it return to_enum(:each) unless block_given?, and return self.
  • Do not mutate the collection while each is running. For arrays this can skip or repeat items.
  • Enumerable methods that need to see everything (sort, min, group_by, to_a) read the whole collection into memory. For endless data, use lazy, first, take_while or find.
  • When your class mostly wraps an array, you can delegate (see Forwardable and Delegation) or simply subclass Array, but delegation through each plus Enumerable keeps your public surface small and your internals private.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the minimum your class must define to make include Enumerable useful?

    Enumerable builds all its methods on top of each, which yields the items. <=> is only needed for sorting and min/max of the items.
  2. 2. What does Enumerable#select return when the receiver is your own class that includes Enumerable?

    Enumerable methods collect results in a plain Array. Hash overrides a few of them (select, reject) to keep its own type, custom classes do not.
  3. 3. Why write return to_enum(:each) unless block_given? at the start of each?

    Without a block, each returns an Enumerator, which supports next, with_index, each_slice and more. Without the guard, yield raises LocalJumpError.
  4. 4. You call fib.select(&:even?) on an endless Enumerable. What happens, and what is the fix?

    select eagerly walks every item. Calling lazy first defers the work so first(5) can stop after five matches.
  5. 5. Which module do you include to get <, >, between? and clamp from a <=> method?

    Comparable builds the comparison operators from <=>. Enumerable is for collections that define each.

Summary

  • Define each (yielding items), include Enumerable, and your class gets map, select, sort_by, reduce, min_by, group_by, each_slice and about forty more.
  • Return to_enum(:each) when no block is given, and return self from each.
  • Enumerable methods return arrays; wrap the result if you need your own type.
  • A class with include Enumerable but no each raises NoMethodError the first time you use a method.
  • sort, min and max need the items to define <=>; sort_by, min_by and max_by only need comparable keys.
  • Use lazy with endless or huge sources so work stops as soon as you have enough.
  • Enumerable is for collections, Comparable is for single objects with an order.

Next: Comparable