← Lesson shelf

Ruby workshop · Enumerable

The Last Tram

A pocket timetable lists routes, trips, and stops. Give it one Ruby method that hands the reader a single stop at a time.

Predict the stops

Pocket timetable

⇄ Transfer stop Times are local to the fictional network.

Predict the stop order

Read each route in print order. Finish its trips from top to bottom and each trip’s stops from left to right. Keep repeated visits. A trip with no stops yields nothing.

Follow one yield

each supplies the stop record, including its name, time, and transfer flag. map collects what a block returns. select keeps each original stop whose block returns a truthy value.

Call each without a block to get an Enumerator. Its next method advances one stop each time.

Read the timetable again ↑

Write the Ruby

The starter yields an entire route. Run the checks, then fix TramTimetable#each so the caller receives one original stop record per visit. Return the timetable after yielding to a block.

Download the Ruby kit

ZIP · Starter, two timetables, six checks, and a worked answer

Run the independent checks

Unzip the kit, enter the last-tram-ruby folder, and run the starter. After editing starter.rb, rerun the same command. The second command checks the supplied answer.

ruby check.rb
ruby check.rb --answer
Open the worked method
def each
  return enum_for(:each) unless block_given?

  @routes.each do |route|
    route.fetch("trips").each do |trip|
      trip.fetch("stops").each do |stop|
        yield stop
      end
    end
  end
  self
end

Each block takes one step down the timetable. Only the innermost block holds a stop record. The early return creates a cursor for a caller who wants to choose when to advance.

Notes from the workshop

This November 2026 exercise, its fictional timetable, and its code were developed for Charles Lee’s workshop with Codex. Its historical starting point was CoderSchool’s Advanced Ruby course. Harley Trung authored the linked assignment commit on 11 July 2016. CoderSchool’s 2016 assignment.

Ruby’s reference explains how each feeds Enumerable, how enum_for creates a cursor, and how next signals the end of an iteration. Enumerable · Object#enum_for · Enumerator.