What is Enumerable in Ruby: Explanation and Examples
Enumerable in Ruby is a module that provides a set of useful methods to work with collections like arrays and hashes. It allows you to loop, search, sort, and manipulate data easily by mixing it into classes that define an each method.How It Works
Think of Enumerable as a toolbox full of handy tools for collections of items, like lists or groups. When a class includes Enumerable, it promises to have a way to go through each item one by one using an each method. This is like saying, "I know how to walk through my items." Once this is set, Enumerable gives the class many ready-made methods to do things like find items, count them, or sort them.
Imagine you have a basket of fruits. If you can pick each fruit one by one, Enumerable helps you do tasks like "find the biggest fruit" or "count how many apples" without writing the steps yourself. It saves time and makes your code cleaner.
Example
This example shows how Enumerable works with an array. The array has many methods from Enumerable like map and select to change or filter items.
numbers = [1, 2, 3, 4, 5] even_numbers = numbers.select { |n| n.even? } squared = numbers.map { |n| n * n } puts "Even numbers: #{even_numbers}" puts "Squares: #{squared}"
When to Use
Use Enumerable whenever you have a collection of items and want to perform common tasks like searching, filtering, sorting, or counting. It is perfect for arrays, hashes, or any custom class that can provide an each method.
For example, if you build a class to hold a list of books, including Enumerable lets you easily find books by author or count how many books are available without extra code. It helps keep your programs simple and powerful.
Key Points
- Enumerable is a module that adds many useful methods for collections.
- It requires the class to define an
eachmethod to work. - Common methods include
map,select,find, andsort. - It helps write cleaner and shorter code when working with lists or groups of items.