An Enumerable Module in Ruby
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:
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:
The Enumerable module consists of several methods like:
- Transversal methods (
map
,delete_if
,select
, etc) - Sorting methods (
sort
,sort_by
, etc) - 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 toeach
method and some methods likemax
,min
orsort
call<=>
operator.Some methods like
count
andtake
are implemented inArray
class instead of using method fromEnumerable
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