0
0
RubyConceptBeginner · 3 min read

What is Enumerable Module in Ruby: Explanation and Examples

The Enumerable module in Ruby is a collection of methods that add useful iteration and searching capabilities to classes like Array and Hash. It works by requiring the class to define an each method, then provides many helpful methods like map, select, and reduce.
⚙️

How It Works

The Enumerable module is like a toolbox full of handy methods that help you work with collections of items, such as lists or groups of data. Imagine you have a basket of fruits, and you want to pick only the red ones or count how many fruits you have. Instead of writing the same steps over and over, Enumerable gives you ready-made tools to do these tasks easily.

To use these tools, your basket (or class) needs to know how to go through each fruit one by one. This is done by defining an each method that tells Ruby how to loop through the items. Once each is set, Enumerable adds many useful methods that use this looping to perform actions like filtering, transforming, or combining items.

💻

Example

This example shows how Enumerable works with an Array. We use select to pick even numbers and map to double each number.

ruby
numbers = [1, 2, 3, 4, 5]
even_numbers = numbers.select { |n| n.even? }
doubled = numbers.map { |n| n * 2 }

puts "Even numbers: #{even_numbers}"
puts "Doubled numbers: #{doubled}"
Output
Even numbers: [2, 4] Doubled numbers: [2, 4, 6, 8, 10]
🎯

When to Use

Use the Enumerable module whenever you want to add powerful and easy-to-use iteration methods to your custom classes that hold collections of items. For example, if you create a class to manage a list of books, you can include Enumerable and define each to loop through the books. Then you get access to methods like find, select, and sort without extra work.

This saves time and makes your code cleaner when working with groups of data, filtering items, transforming lists, or calculating results from collections.

Key Points

  • Enumerable adds many useful methods for working with collections.
  • It requires the class to define an each method.
  • Common methods include map, select, reduce, and find.
  • It works with built-in classes like Array and Hash, and can be included in your own classes.
  • Using Enumerable makes code simpler and more readable when handling lists of items.

Key Takeaways

Enumerable provides many helpful methods for iterating and searching collections in Ruby.
To use Enumerable, your class must define an each method to loop through items.
Enumerable methods like map and select simplify working with lists and data sets.
Including Enumerable in your custom classes adds powerful collection tools easily.
Enumerable helps write cleaner, more readable code when handling groups of objects.