0
0
RubyConceptBeginner · 3 min read

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.

ruby
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}"
Output
Even numbers: [2, 4] Squares: [1, 4, 9, 16, 25]
🎯

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 each method to work.
  • Common methods include map, select, find, and sort.
  • It helps write cleaner and shorter code when working with lists or groups of items.

Key Takeaways

Enumerable provides many helpful methods for working with collections in Ruby.
To use Enumerable, a class must implement the each method to iterate items.
Enumerable methods simplify tasks like filtering, searching, and transforming data.
It works with arrays, hashes, and any custom collection class.
Using Enumerable leads to cleaner and more readable code.