0Pricing
Ruby Academy · Lesson

Writing Custom each

Implement iteration.

Implement Iteration

Ruby's iteration revolves around one method: each. By writing your own each, you decide how a collection is traversed and unlock the whole iteration ecosystem.

class Trio
  def each
    yield 1
    yield 2
    yield 3
  end
end
Trio.new.each { |n| puts n }

each Yields Values

Inside each, call yield once per element. The block the caller supplies receives each value in turn.

class Days
  NAMES = ["Mon", "Tue", "Wed"]
  def each
    NAMES.each { |d| yield d }
  end
end
Days.new.each { |day| puts day }

All lessons in this course

  1. Writing Custom each
  2. Including Enumerable
  3. Lazy Enumerators
  4. Enumerator Objects
← Back to Ruby Academy