0Pricing
Ruby Academy · Lesson

Including Enumerable

Get map/select for free.

Get map/select for Free

Once your class has each, mixing in Enumerable instantly gives you map, select, reduce, sort, min, max, and many more, all built on your each.

class Bag
  include Enumerable
  def initialize(*x); @x = x; end
  def each; @x.each { |i| yield i }; end
end
p Bag.new(1, 2, 3).map { |n| n * 10 }

The Contract

The deal is simple: include Enumerable and define each. Enumerable calls your each internally to power everything else.

class Squares
  include Enumerable
  def initialize(n); @n = n; end
  def each
    (1..@n).each { |i| yield i * i }
  end
end
p Squares.new(5).to_a

All lessons in this course

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