DEV Community

Sandip Mane
Sandip Mane

Posted on

Enumerable Module in Ruby

Ruby's Enumerable module adds magical methods
to classes like Array and Hash.
In this post, we will learn to implement enumeration with an example.

Enumeration

Enumeration is a process of traversing over objects one by one.
To make a class enumerable, we can include Enumerable module.
Thus, giving access to methods like #map, #filter, #count, #include?, #any?, #uniq and a lot more!

#each

Enumerable module maily relies on #each method on the implementing class.
The #each method is implemented such that when a block is passed,
the contents of the collection are evaluated.

> [1, 2, 3].each { |a| a }
=> [1, 2, 3]

Enumerator

Enumerator is a class which allows manual iteration over an enumerator object.
When #each is called without a block, it returns a new Enumerator object
hence allowing to chain multiple enumerators.

> enumerator = %w[foo bar baz].each
> enumerator
=> #<Enumerator: ["foo", "bar", "baz"]:each>

> enumerator.map.with_index { |w, i| "#{i}:#{w}" }
=> ["0:foo", "1:bar", "2:baz"]

Check out my full post here for an example of a LinkedList with enumerable module.
https://www.sandipmane.dev/exploring-rubys-enumerable-module

Top comments (0)