When to Define Your Own Custom Ruby Iterator?

General rule of thumb is if you have a collection of objects, you should build custom iterators so that users could readily use them like they do with other collection such as Array, Hash, File, etc.

The easiest way to do this is to mix-in the Enumerable module. The only requirement is to define an each method in your class which will provide Enumerable with your collection objects.

Let’s take a look at an example. Let’s say you’re a property owner with a few properties in various cities.

Now, what if we want to iterate through the addresses in LA?

So how do we implement an iterator, much like we’ve seen with other collections such as Arrays and Hashes? We define an each method in our PropertyList class.

Now what if we want to get the total square footage of all the properties in LA that have at more than 3 rooms? Naturally we think of the select and reduce methods, but those belong to the Enumerable module.

Aha! As mentioned, all we have to do is define an each method in the host class to mix in Enumerable. Our final class looks like this:

and we get an output of: “Total SQ/FT for LA Properties: 10000” which is correct.

Now let’s level up some more. How about we build our own Enumerable module. We want to get this to work:

All we have to do is define our own module and include it in the PropertyList class:

With this we just “Include EstateEnumerable” instead of “Enumerable” and we’ll get this as the output:

This hopefully gives you a glimpse of what Ruby blocks are capable of.

Leave a Reply

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