MATTENOBLE

rubygem

Ruby Enumerables

If you’re writing any type of API client library, you’ll probably need some sort of Collection class that’s iterable. It’s quite simple, but pretty powerful; most things in Ruby are.

It’s All About Each

The Ruby stdlib has this handy module named Enumerable. It basically means that if you mix it into a class which responds to each, you get all the fanciness that is select, map, all?, etc.

This sounded odd to me at first. How would implementing the method you use to iterate an object… make it iterable? It only feels weird because we’re used to each being an interface, not an implementation. It plays both roles!

An Egg Sample

class Carton
  include Enumerable

  def each
    @eggs.each { |egg| yield egg }
  end

  def drop
    @eggs = []
  end
end

Now whenever you create a Carton object with a bunch of eggs, you’ll be able to iterate over those eggs one at a time. The eggs themselves can live in an Array, Hash, whatever. The important thing is to yield them one at a time via each.

With the above code, a Carton object can now do everything any other enumerable object can, but with the added bonus of breaking all over the fucking parking lot…