How to Write Your Own Iterators in Ruby

Generally if your class has an array/hash, sometimes you don’t want to expose the implementation of those collections outside of the object. Creating your own iterator will make your object easier to use.

I think another way to demonstrate this is to show how the “each” and “times” methods work in Ruby. There isn’t much magic involved. For times all you have to do is open up the Integer class and define your own with a while loop:

As for each it’s very similar:

Hopefully this helps demystify these methods we use and love so much.

Leave a Reply

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