# How to Create a Custom Enumerable

DevFeed: [How to Create a Custom Enumerable](<https://devfeed.tech/articles/how-to-create-a-custom-enumerable-21043.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2015/09/27/how-to-create-a-custom-enumerable/>)

Published: 2015-09-27T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>)

Tags: [examples](<https://devfeed.tech/tags/examples.md>), [how-to](<https://devfeed.tech/tags/how-to.md>), [ruby](<https://devfeed.tech/tags/ruby.md>)

## AI overview

A Ruby tutorial explains how to create a custom collection class that behaves as an Enumerable. Using a DogKennel example, it covers including the Enumerable module, defining the each method required by Enumerable's iterative methods, and considering comparison behavior.

## Source excerpt

Ruby is a wonderfully flexible language. An example of this flexibility is in the ability to define a custom collection class that acts as an Enumerable object. In Ruby, a collection that acts as an Enumerable is basically a class which holds a list of objects and exposes helpful methods for iteration and collection. An example of this pattern built into Ruby is the Array class. In keeping with a theme, let us assume that an application about dogs exists. In this example, a DogKennel class exists that will hold information about each dog in the kennel and detailed information about said kennel. We can also assume that this class is meant to be used as a collection of dogs, exposing helper methods for information about the kennel. Why would we use this collection class over a typical Array? One reason might be that the consumer of this class expects a list of dogs and some additional metadata. That metadata can be easily exposed in this class without having to wrap the class or extract the metadata from an included Hash. class DogKennel attr_reader :dogs, :location, :operating_hours def initialize(dogs, location, operating_hours) @dogs = dogs @location = location @operating_hours = operating_hours end end 1. Add include Enumerable To make our DogKennel into something that can iterate over its dogs easily, we can add the Enumerable module. The desired functionality will have iterative functions as instance methods, so include will be used: class DogKennel include Enumerable attr_reader :dogs, :location, :operating_hours def initialize(dogs, location, operating_hours) @dogs = dogs @location = location @operating_hours = operating_hours end end This include will allow the DogKennel class to inherit a large number of useful methods; however, none of these methods are able to be used until a basic iterative each method is defined. If a method such as map is called in this state, the DogKennel class will throw a NoMethodError until the each method is defined. 2. Define an