..flipping the script..

Becoming Enumerable

Published August 18, 2011 - 0 Comments

My first post on RubySource, hasn’t been published as of 08/18/2011, covers using mixin’s in Ruby. Shortly after writing that article I ran across a presentation titled “The Enumerable Module” presented by Haris Amin at Cascadia Ruby Conf 2011. The general idea is that you can make your classes enumerable (e.g. have lots of cool methods you’re used to seeing when working with Arrays, Hashes, etc).

Since the process of making a class enumerable requires the use of mixin’s I figured I provide a brief demonstration of how to do it.

class Followers
    include Enumerable

    def initialize
        @followers = []
    end

    def add_follower(name)
        @followers << name
    end

    def degrees_of_separation(name)
        # calculate
    end

    # must implement the each method
    def each
        # simple in this example
        @followers.each do |val|
            yield val
        end
    end
end

The Followers class stores an array of values which we iterate over in our implementation of the #each method.

Check it out:

f = Followers.new
f.add_follower 'shaun'
f.add_follower 'cliff'
f.add_follower 'sean'
f.add_follower 'nick'
f.add_follower 'tim'

f.find_all {|val|
  val.match /^s/i
}
# output: ["shaun", "sean"]

f.collect do |val|
  val.upcase
end
# result: ["SHAUN", "CLIFF", ...]

Sorry for the lame example (e.g. “followers”) but I think you get the point.