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_aAll lessons in this course
- Writing Custom each
- Including Enumerable
- Lazy Enumerators
- Enumerator Objects