Thuta Learning
Ruby
IntermediateProgrammingBeginner

Enumerable & Enumerator

RubyLesson 1540 min

What you'll walk away with

  • Write each with yield in your own class and include Enumerable to inherit the collection methods
  • Explain why each starts with return to_enum(:each) unless block_given?
  • Walk a sequence with next, peek, rewind and StopIteration, and build one with Enumerator.new
  • Use lazy enumerators to handle infinite sequences safely and explain how they differ from eager chains
  • Include Comparable with a single <=> so your objects can be sorted, min'd and max'd

Explain it simply

Explain it simply

Array, Hash and Range share methods such as map, select, sort and min because they all borrow the same bundle of methods, called Enumerable. Enumerable asks your class for exactly one thing: an each method that hands over the elements one by one. Write that each, and every other method in the bundle works on your class too.

An Enumerator is an object that represents 'iterate over this using that method'. You get one when you call an iterator without a block. Because you can ask an enumerator for the next item only when you need it, it can even handle lists that never end.

Problem → Why → Solution

The problem: your class is not a collection yet

Suppose you wrote a Playlist class that keeps songs in an array. You want to call map, select and count on a Playlist, but Ruby does not treat an object as a collection just because it holds one. You end up with two bad options: write count, select and sort yourself one by one, or expose the inner array to the outside. This code tries calling map.

playlist_problem.rb
class Playlist
  def initialize(*songs)
    @songs = songs
  end
end

playlist = Playlist.new("Alpha", "Delta Wave")
playlist.map(&:upcase)
# NoMethodError: undefined method 'map' for an instance of Playlist

How can one method unlock fifty?

map, select, sort and the rest are all written on top of a single request: give me the elements one at a time. So Ruby writes them once inside the Enumerable module and lets every class borrow them by supplying each. Add each and include Enumerable to Playlist and the problem disappears.

Core concept: write each, borrow the rest

Enumerable is a module, a bundle of methods that you mix into a class with include. It requires exactly one thing from the class: an each method that yields every element. Every other Enumerable method (map, select, reduce, sort, min, max, first, include?, each_slice, group_by and dozens more) is written in terms of your each. Array, Hash, Range, Struct and File all work this way, which is why they share one vocabulary.

Your each must follow two rules. It has to yield every element to the block, and when no block is given it should return an Enumerator (return to_enum(:each) unless block_given?). Enumerable's own methods always pass a block, so they work without the guard; the guard is for callers who write playlist.each.with_index(1) or playlist.each.next with no block. Without the guard those calls fail with LocalJumpError: no block given (yield).

An Enumerator is an object that represents 'iterate over this using that method'. You get one from nearly any iterator called without a block: [1, 2, 3].each, 5.times, 'abc'.each_char. Enumerators are themselves Enumerable, so you can keep chaining. They also come in two styles. Internal iteration is what you have used so far: the method pushes elements into your block. External iteration flips it: you pull elements one at a time with next, and peek looks at the next one without consuming it. When the elements run out, next raises StopIteration, and loop rescues that error silently, so loop { puts e.next } walks an enumerator exactly once.

Enumerator.new lets you build a sequence from scratch by writing a block that pushes values into a yielder with y << value. The block runs only when someone asks for the next value, so it can describe an infinite sequence safely. Add lazy and you get an Enumerator::Lazy, whose map, select and reject do not run immediately; they build a pipeline, and nothing is computed until a method such as first(n), take(n).to_a or force pulls values through. That is how (1..Float::INFINITY).lazy.select(&:even?).first(4) returns a result instead of hanging.

Mental model: define each, get the rest
  1. You write each (yield every element)
  2. Enumerable builds methods on each
  3. Enumerator turns each into next/peek
  4. lazy delays work until you ask

One method, each, is the whole contract; everything else is borrowed.

General pattern

ruby
class Collection
  include Enumerable

  def each
    return to_enum(:each) unless block_given?
    # yield every element, one at a time
  end
end

sequence = Enumerator.new { |y| y << value }

include Enumerable mixes in the bundle, and each says how to walk this class's elements. The guard line returns an Enumerator when no block is given. The last line is the class-free form: Enumerator.new builds a sequence, and y << value hands out the next value.

Example: a Playlist that becomes a collection

This Playlist class writes just one each and includes Enumerable. Then watch sort, map, select, min_by and friends work on a playlist as if they had been written for it. initialize stores the songs when the object is built; the Initialize lesson explains it in detail.

The class contains no line about counting songs or sorting them. All of it comes from each.

playlist.rb
class Playlist
  include Enumerable

  def initialize(*songs)
    @songs = songs
  end

  def each
    return to_enum(:each) unless block_given?
    @songs.each { |song| yield song }
    self
  end
end

playlist = Playlist.new("Blue Hour", "Alpha", "Delta Wave", "Charlie")

puts playlist.count
p playlist.sort
p playlist.map(&:length)
p playlist.select { |song| song.length > 6 }
puts playlist.min_by(&:length)
p playlist.first(2)
puts playlist.include?("Alpha")
p playlist.each_slice(2).to_a
p playlist.each_with_index.map { |song, i| "#{i + 1}. #{song}" }

Code breakdown

  1. includeinclude Enumerable

    This single line mixes the Enumerable methods into Playlist. They still need an each to call, so nothing works until each exists.

  2. guardreturn to_enum(:each) unless block_given?

    Calling playlist.each with no block returns an Enumerator, so playlist.each.next and playlist.each.with_index(1) both work.

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

    The key line. It walks the inner array and yields each song to whichever block was passed to the Playlist. That is what powers map, select and sort.

  4. sortp playlist.sort

    Enumerable gathers the elements through each and orders them with String's <=>, so the result is alphabetical. Note that sort returns a new Array, not a Playlist.

  5. chainplaylist.each_with_index.map { |song, i| "#{i + 1}. #{song}" }

    each_with_index is called without a block, so it returns an Enumerator, and map then transforms those [song, index] pairs. Enumerators are Enumerable, which is why chaining works.

You should see
4
["Alpha", "Blue Hour", "Charlie", "Delta Wave"]
[9, 5, 10, 7]
["Blue Hour", "Delta Wave", "Charlie"]
Alpha
["Blue Hour", "Alpha"]
true
[["Blue Hour", "Alpha"], ["Delta Wave", "Charlie"]]
["1. Blue Hour", "2. Alpha", "3. Delta Wave", "4. Charlie"]

External enumerators: next, peek and Enumerator.new

next pulls one element at a time, peek looks at the next one without consuming it, and rewind sends the enumerator back to the start. Calling next after the elements run out raises StopIteration with the message iteration reached an end, and loop do ... end rescues it silently so the loop simply stops. Enumerator.new gives you a yielder y and lets you write a block that produces values with y << value. In the Fibonacci generator below the inner loop is endless, but it only runs when a value is requested, so that is fine.

external.rb
e = [10, 20, 30].each
puts e.next                     # 10
puts e.peek                     # 20  (peek does not move forward)
puts e.next                     # 20
puts e.next                     # 30
begin
  e.next
rescue StopIteration => err
  puts "done: #{err.message}"   # done: iteration reached an end
end
e.rewind
puts e.next                     # 10 again

letters = %w[a b c].each
loop { puts letters.next }      # loop swallows StopIteration and ends quietly
puts "finished"

fib = Enumerator.new do |y|
  a, b = 0, 1
  loop do
    y << a
    a, b = b, a + b
  end
end
p fib.take(8)                   # [0, 1, 1, 2, 3, 5, 8, 13]
p fib.lazy.select(&:even?).first(5)   # [0, 2, 8, 34, 144]

Lazy enumerators: compute only on demand

In an ordinary (eager) chain, map processes every element first and passes the whole result to select. In a lazy chain each element travels through map and select one at a time, and the chain stops the moment a terminal method such as first(1) has what it needs. The log below shows this directly. An endless range mapped without lazy never finishes.

text
Eager versus lazy work for first(1)
-----------------------------------
Eager  map 1..6  ->  [10,20,30,40,50,60]
       select all 6 ->  [30,40,50,60]
       first(1)     ->  [30]            12 steps of work

Lazy   1 -> map -> select (10: no)
       2 -> map -> select (20: no)
       3 -> map -> select (30: yes) -> first(1) is satisfied, stop
                                        6 steps of work
lazy.rb
evens_squared = (1..Float::INFINITY).lazy.select(&:even?).map { |n| n * n }
p evens_squared.first(4)          # [4, 16, 36, 64]

p [1, 2, 3, 4, 5].lazy.select(&:odd?).map { |n| n * 10 }.first(2)   # [10, 30]

log = []
result = (1..6).lazy
  .map    { |n| log << "map #{n}";    n * 10 }
  .select { |n| log << "select #{n}"; n > 20 }
  .first(1)
p result                          # [30]
puts log.join(", ")               # map 1, select 10, map 2, select 20, map 3, select 30
puts log.size                     # 6 (an eager chain would log 12)

To get results out of a lazy chain, call first(n), take(n).to_a or force on it. Printing a lazy enumerator directly shows something like #<Enumerator::Lazy: ...>, not the values. Lazy adds a small cost per element, so for tiny arrays the eager version is simpler and usually faster.

Comparable: giving your own objects an order

Enumerable's sort, min and max only work when the elements can be compared with <=>. Write one <=> for your class and include Comparable, and you get <, <=, ==, >, >=, between? and clamp for free. <=> must return -1, 0 or 1, or nil for objects that cannot be compared, in which case Comparable raises ArgumentError. Sorting versions as strings puts "1.10" before "1.2" because strings compare character by character, so comparing major and minor as numbers, as below, is the right approach.

comparable.rb
class Version
  include Comparable

  attr_reader :major, :minor

  def initialize(major, minor)
    @major = major
    @minor = minor
  end

  def <=>(other)
    return nil unless other.is_a?(Version)

    [major, minor] <=> [other.major, other.minor]
  end

  def to_s
    "#{major}.#{minor}"
  end
end

versions = [Version.new(1, 10), Version.new(1, 2), Version.new(2, 0)]
puts versions.min                              # 1.2
puts versions.max                              # 2.0
puts versions.sort.join(", ")                  # 1.2, 1.10, 2.0
puts Version.new(1, 2) < Version.new(1, 10)    # true
puts Version.new(1, 5).between?(Version.new(1, 2), Version.new(1, 10))   # true
puts Version.new(3, 0).clamp(Version.new(1, 0), Version.new(2, 0))       # 2.0
puts Version.new(1, 2) == Version.new(1, 2)    # true: == is built from <=>
begin
  Version.new(1, 2) < 5
rescue ArgumentError => e
  puts e.message                               # comparison of Version with 5 failed
end

attr_reader and initialize appear here only as tools; the next lessons explain them properly. The point is that one <=> buys you about seven comparison operations. Even == comes from this <=>, while equal? still asks whether two names refer to the very same object and stays false.

In real projects

Where this shows up in real projects

Collections you meet in real projects are almost all Enumerable: Set, Struct, Range, Hash, CSV::Table, Dir and the lines of a File. A custom class such as OrderBook, Inventory or ShoppingCart earns the same power with include Enumerable and a six-line each, and callers then write cart.select(&:taxable?).sum(&:price) without you writing either method. Add Comparable for value-like objects such as versions, money amounts and dates so that sort, min, max and between? just work.

Lazy enumerators matter when the source is large or endless. File.foreach('app.log').lazy.select { |line| line.include?('ERROR') }.first(20) reads only as much of a multi-gigabyte log as it needs, and Enumerator.new can wrap paginated API calls or a database cursor as a stream that fetches the next page only when asked. The cost is a little overhead per element, so for small arrays the plain eager version is simpler and usually faster.

Common mistakes

Common mistakes

1. Forgetting to yield inside each

Writing def each; @songs; end only returns the array and never calls the block. map then collects nothing and quietly returns [], and count returns 0, which is a silent bug. each must yield every element, usually by delegating: @songs.each { |s| yield s }. If you include Enumerable and write no each at all, you get NoMethodError: undefined method 'each' for an instance of Playlist.

2. Printing a lazy chain instead of forcing it

Printing (1..Float::INFINITY).lazy.map { |n| n * 2 } shows #<Enumerator::Lazy: ...>, not numbers, because lazy methods only build a recipe. Run it with first(n) or take(n).to_a / force. The reverse mistake exists too: forgetting .lazy on an endless range, as in (1..Float::INFINITY).map { ... }, never finishes.

3. Calling next after the end

Once an enumerator has handed out every element, calling next raises StopIteration: iteration reached an end, and the program stops unless you use loop or rescue it. Call rewind to start over, and prefer loop { e.next } to calling next yourself inside a while.

4. Sorting version numbers as strings

["1.10", "1.2"].sort returns ["1.10", "1.2"], because strings compare character by character and "1.1" is smaller than "1.2". To compare as numbers, write <=> on the major and minor numbers and include Comparable.

Best practices

Best practices

  • Give every collection-like class include Enumerable and just an each; do not re-implement map, select and count yourself.
  • Write each with yield and add the to_enum guard so callers such as playlist.each.with_index(1) work.
  • Use lazy for endless or very large sources and finish the chain with first(n) or take(n).to_a.
  • For value-like objects write one <=> and include Comparable, returning nil for objects that cannot be compared.

Mini challenge

Mini challenge: a StudyLog collection

Build a StudyLog class that stores the minutes studied each day. Write only each and borrow everything else from Enumerable, then finish with a lazy Enumerator.

  • StudyLog includes Enumerable and its each yields every minutes value (with the to_enum guard)
  • Use sum, max and count with a block to print the total, the longest session and the number of days above average
  • Use each_cons(2) to print how many days had more minutes than the day before
  • Use Enumerator.new to generate multiples of 7, then lazy and select to print the first 3 above 50
study_log.rb
class StudyLog
  include Enumerable

  # TODO: initialize(minutes) stores the array
  # TODO: each yields every value, with the to_enum guard
end

log = StudyLog.new([30, 45, 20, 50, 50])

# TODO: print the total, the longest session and the days above average
# TODO: print how many days rose compared with the day before (each_cons)
# TODO: an Enumerator.new that yields 7, 14, 21, ... and a lazy select for > 50

Expected: Total: 195 minutes Longest: 50 minutes Days above average: 3 Rising days: 2 Multiples of 7 above 50: [56, 63, 70]

Show hint

For the average use average = log.sum.fdiv(log.count); log.count { |m| m > average } counts only the matches. Inside Enumerator.new start n = 0 and write loop { y << (n += 7) }, then call .lazy.select { ... }.first(3).

Show solution
study_log.rb
class StudyLog
  include Enumerable

  def initialize(minutes)
    @minutes = minutes
  end

  def each
    return to_enum(:each) unless block_given?
    @minutes.each { |value| yield value }
    self
  end
end

log = StudyLog.new([30, 45, 20, 50, 50])

puts "Total: #{log.sum} minutes"
puts "Longest: #{log.max} minutes"
average = log.sum.fdiv(log.count)
puts "Days above average: #{log.count { |minutes| minutes > average }}"
puts "Rising days: #{log.each_cons(2).count { |before, after| after > before }}"

multiples = Enumerator.new do |y|
  n = 0
  loop { y << (n += 7) }
end
puts "Multiples of 7 above 50: #{multiples.lazy.select { |n| n > 50 }.first(3)}"

Quick quiz 1 / 3

A Playlist class includes Enumerable but defines no each. What happens on playlist.map { |s| s }?

Quick quiz 2 / 3

What does (1..Float::INFINITY).lazy.map { |n| n * 2 }.first(3) return?

Quick quiz 3 / 3

After e = [1, 2].each, what happens on the third call to e.next?

What to remember

  • Enumerable asks for just one method, each, and returns dozens of others such as map, select, sort, min and first; each must yield every element.
  • Start each with return to_enum(:each) unless block_given? so it returns an Enumerator without a block; enumerators are Enumerable themselves, so chaining works.
  • External enumerators use next, peek and rewind and raise StopIteration at the end, which loop rescues; Enumerator.new builds a sequence from scratch.
  • lazy defers work until a terminal method such as first(n) asks for it, which makes endless sequences safe; Comparable turns one <=> into all the comparison methods.

Ruby Enumerator Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.