Skip to Content
Course content

47: The Enumerable Module in Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a recurring pattern when developers start building their own collection classes in Ruby: they assume that Enumerable is a "magic" module that automatically knows how to traverse any object it's mixed into. They'll include Enumerable at the top of their class, try to call .map or .select, and then stare in confusion when Ruby throws a NoMethodError for each.

The "Include and it Works" Fallacy

The misconception is that Enumerable provides the logic for how to iterate. It doesn't. It provides a massive library of high-level tools (like find_all, group_by, and reduce) that all rely on a single, specific contract: the existence of an each method.

# This is what the misconception looks like in code
class Playlist
  include Enumerable

  def initialize(songs)
    @songs = songs # assume this is an array
  end
end

my_list = Playlist.new(["Song A", "Song B"])
my_list.map { |s| s.upcase } 
# NoMethodError (undefined method `each' for #<Playlist:0x000...>)

As you can see, Enumerable is essentially a set of plugins. But these plugins are useless if there's no engine to drive them. In this case, each is the engine.

Enumerable as a Mixin Powered by each

To make Enumerable work, you have to implement the each method yourself. This method is the "source of truth" for how your object should be stepped through. Once each exists, Enumerable suddenly "unlocks" dozens of other methods because it simply calls your each method internally to do its work.

Let's fix the Playlist example. I'll define each so that it yields every song in the internal array to the block provided.

class Playlist
  include Enumerable

  def initialize(songs)
    @songs = songs
  end

  def each
    @songs.each do |song|
      yield song
    end
  end
end

my_list = Playlist.new(["Song A", "Song B", "Song C"])

# Now this works! .select is provided by Enumerable, but it uses our .each
rock_songs = my_list.select { |s| s.include?("Rock") } 

I want you to think of Enumerable as a layer of abstraction. You define the primitive (the each method), and Ruby gives you the conveniences (everything else). This is a beautiful example of the "Composition over Inheritance" philosophy in Ruby.

The Pro Move: Returning an Enumerator

If you look at the source code for Ruby's core Array class, you'll notice that each doesn't just yield values—it can also return an Enumerator object if no block is given. If you want your custom collection to feel like a first-class Ruby citizen, you should mimic this behavior.

By adding a simple check for the block, you allow your users to chain methods or call .with_index on your collection, which is an incredibly powerful pattern.

class Playlist
  include Enumerable

  def initialize(songs)
    @songs = songs
  end

  def each
    # If the user didn't provide a block, return an Enumerator
    return to_enum(:each) unless block_given?

    @songs.each { |song| yield song }
  end
end

my_list = Playlist.new(["Song A", "Song B", "Song C"])

# Because we returned an Enumerator, we can do this:
my_list.each.with_index { |song, i| puts "#{i + 1}. #{song}" }

Adding return to_enum(:each) unless block_given? might seem like a pedantic detail, but it's the difference between a script that "just works" and a professional library that integrates seamlessly with the rest of the Ruby ecosystem.




📋 Practical Task

Build a TransactionHistory Filter

You are building a financial ledger system. Create a class called TransactionHistory that stores a list of transaction hashes (each hash should have an :amount and a :category).

Your task is to:

  • Include the Enumerable module.
  • Implement the each method so that the class is enumerable (ensure it handles the case where no block is given by returning an enumerator).
  • Using the power of Enumerable (without writing new methods inside the class), perform the following operations on an instance of TransactionHistory:
    1. Find the total sum of all transactions using reduce (or sum).
    2. Filter the transactions to find only those in the "Food" category using select.
    3. Find the first transaction that exceeds $100 using find.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.