DEV Community

Sandip Mane
Sandip Mane

Posted on

1 4

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs