0Pricing
Ruby Academy · Lesson

Writing Custom each

Implement iteration.

Writing Custom each is a free Ruby Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Ruby Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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 }

Storing Internal Data

Usually each walks over data held in an instance variable.

class Stack
  def initialize
    @items = []
  end
  def push(x); @items << x; self; end
  def each
    @items.each { |i| yield i }
  end
end
s = Stack.new
s.push(10).push(20)
s.each { |x| puts x }

Custom Traversal Order

Your each can iterate in any order you like, for example reverse.

class Reversed
  def initialize(arr); @arr = arr; end
  def each
    i = @arr.length - 1
    while i >= 0
      yield @arr[i]
      i -= 1
    end
  end
end
Reversed.new([1, 2, 3]).each { |x| puts x }

Yielding Multiple Values

yield can pass more than one value, which the block receives as multiple parameters, like a hash's key and value.

class Pairs
  def each
    yield :a, 1
    yield :b, 2
  end
end
Pairs.new.each { |key, value| puts "#{key}=#{value}" }

each Returns self

By convention each returns the collection itself so calls can chain. Returning self from each matches built-in behavior.

class Box
  def initialize(*x); @x = x; end
  def each
    @x.each { |i| yield i }
    self
  end
end
result = Box.new(1, 2).each { |i| }
puts result.class

Using block_given?

Guard against a missing block so a bare each does not crash, often by returning an enumerator (covered later).

class List
  def initialize(*x); @x = x; end
  def each
    return @x.to_enum unless block_given?
    @x.each { |i| yield i }
  end
end
puts List.new(5, 6).each.class

Driving Other Methods

Once each exists you can build other methods on top of it within the same class.

class Numbers
  def initialize(*n); @n = n; end
  def each; @n.each { |i| yield i }; end
  def total
    sum = 0
    each { |i| sum += i }
    sum
  end
end
puts Numbers.new(1, 2, 3, 4).total

Computed Sequences

each need not store anything; it can generate values on the fly.

class Evens
  def initialize(limit); @limit = limit; end
  def each
    n = 0
    while n <= @limit
      yield n
      n += 2
    end
  end
end
Evens.new(8).each { |x| puts x }

The Foundation for Enumerable

Your each is the single building block Enumerable needs. Next lesson you will include it and gain dozens of methods for free.

class Range3
  def each
    (1..3).each { |n| yield n }
  end
end
Range3.new.each { |n| print n }
puts

Putting It Together

Custom each gives you full control of iteration:

  • yield once per element.
  • Traverse in any order, generate values, or yield pairs.
  • Return self by convention.
class Countdown
  def initialize(from); @from = from; end
  def each
    @from.downto(1) { |n| yield n }
  end
end
Countdown.new(3).each { |n| puts n }

Quick Check

Test your understanding of custom each.

Recap

You learned to write a custom each:

  • yield passes elements to the caller's block.
  • You control traversal order and can generate values.
  • Return self by convention.
  • each is the foundation for Enumerable.
class Squares
  def initialize(n); @n = n; end
  def each
    (1..@n).each { |i| yield i * i }
  end
end
Squares.new(4).each { |sq| puts sq }

Frequently asked questions

Is the “Writing Custom each” lesson free?

Yes — the full text of “Writing Custom each” is free to read here on the web, and the Ruby Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Ruby Academy course, upgrade to CoddyKit PRO.

What will I learn in “Writing Custom each”?

Implement iteration. You practise Ruby Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Ruby Academy?

No prior experience is required. Ruby Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Writing Custom each” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Ruby Academy lesson?

Yes. Every Ruby Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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