Examples

As each Enumerable method is explained, we'll use a common set of examples:

  • a simple array of numbers
  • a PetInventory class, which manages a collection of Pet objects
  • a file that contains a list of "pokey things"
  • a LogData class which iterates through Heroku log files in a RAM-friendly way

Array of Numbers

Most examples will start with the simplest Enumerable class: an array called numbers. This is what the value will be:

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

PetInventory Class

We've created a class called PetInventory to demonstrate how any class that maintains a collection of items can use the Enumerable module as a mixin. PetInventory manages inventory for a pet store.

As is common with collection classes, we've also defined a class for the items that will be collected; in this case, Pet objects. Each Pet object in the collection tracks how many of that type of pet the store has in stock, and how many legs that pet has. We could track all sorts of info, but for our examples we'll limit ourselves to just those couple pieces of information.

@inventory = PetInventory.new

Here's our initial pet inventory:

pet legs # in stock
dog 4 100
cat 4 50
fish 0 1000
scorpion 8 1
beetle 6 10,000
monkey 2 2
rock 0 0

All of our examples will start out with this list of pets.

File Data

Ruby's File class uses Enumerable as well. Included in the examples is a file of "pokey things":

@pokey_things = File.open('./data/pokey_things.txt', 'r')

The file itself has the following content:

cactus
poles
knife
cactus holding poles with knives attached

Heroku Log Data

The PetInventory class isn't very useful in real life, so we created the start of a class that can be used to manage Heroku log files. It uses the Enumerable module so that it doesn't have to hold the contents of the entire log file (which could be enormous) into memory.

@requests = LogData.new('./data/heroku.log')

The log file itself has a couple dozen records. You can view it here:

https://github.com/rubycuts/enumerables/blob/master/data/heroku.log

Leave a Reply

Your email address will not be published. Required fields are marked *