What is Enumerable Module in Ruby: Explanation and Examples
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.
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}"
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
eachmethod. - Common methods include
map,select,reduce, andfind. - It works with built-in classes like
ArrayandHash, and can be included in your own classes. - Using
Enumerablemakes code simpler and more readable when handling lists of items.