An Enumerable Module in Ruby

Juzer Shakir
2 min readJul 14, 2021

--

A rich source of methods provided by Ruby that’s available to use by classes.

Prerequisite

This topic will be easier to comprehend if you have the following knowledge:

Table of Contents

Definition

Calling the module

Definition

Enumerable module is a built-in module provided by Ruby which has collection of methods packaged together that are included in other built-in Classes of Ruby such as Array, Hash and Range.

It's designed to provide useful functionality to the classes. Most of the iteration methods like select, reject, delete_if, find etc associated to Array and Hash aren’t actually implemented in these Classes but use include keyword to make Enumerable methods available to these classes.

It's something like this under the hood:

Topics covered in this article on Enumerable Module

The Enumerable module consists of several methods like:

  1. Transversal methods (map, delete_if, select, etc)
  2. Sorting methods (sort, sort_by, etc)
  3. Searching methods (find, find_all, first, etc)

Using an Enumerable module in the class

If an Enumerable module is to be used by a class, then that class should have an each method explicitly declared in it. If a method of an Enumerable is passed with a block, that method will make a call to each method and perform operations of a block in it with the help of yield keyword. That’s the reason why in the above program file enum_01.rb, it has each method defined in class Array and Hash .

What happens if we don’t use each method?

Following output for line #8:

enum.rb:13:in `map': undefined method `each' for #<Klass:0x000055632209f580 @arg="I am from class "> (NoMethodError)

As we give a block to one of the Enumerable methods, map, we see it looks for each method in class Klass and when it can’t find it, it gives NoMethodError.

map method will return an array because its meant to be used for Array class so lets see another more practical example.

For both programs, enum_03.rb & enum_04.rb, it uses each method to successfully perform an operation in a block passed to Enumerable method, map.

List of all Enumerable methods available to use in Ruby Official Documentation.

Almost all methods of Enumerable make call to each method and some methods like max, min or sort call <=> operator.

Some methods like count and take are implemented in Array class instead of using method from Enumerable module to make operations faster.

That’s all important things to know about an Enumerable module.

My previous article: Modules in Ruby
My next article: An Enumerator class in Ruby

--

--