0
0
Rubyprogramming~5 mins

Why Enumerable is Ruby's most powerful module

Choose your learning style9 modes available
Introduction

Enumerable helps you work with collections like lists easily. It gives many ready-made ways to find, sort, and change items without writing extra code.

When you want to search for items in a list, like finding all even numbers.
When you need to sort or order items in a collection.
When you want to transform each item in a list, like doubling all numbers.
When you want to check if any or all items meet a condition.
When you want to count or group items based on some rule.
Syntax
Ruby
module Enumerable
  # You must define an each method in your class
  def each
    # code to loop over items
  end

  # Then you get many methods like map, select, find, etc.
end

Enumerable works by requiring your class to have an each method that goes through all items.

Once each is defined, you get many useful methods for free.

Examples
This class includes Enumerable and defines each. Now it can use Enumerable methods.
Ruby
class MyList
  include Enumerable

  def initialize(items)
    @items = items
  end

  def each
    @items.each { |item| yield item }
  end
end
Using Enumerable's select to get even numbers from the list.
Ruby
list = MyList.new([1, 2, 3, 4])
evens = list.select { |n| n.even? }
puts evens.inspect
Sample Program

This program shows how including Enumerable and defining each lets you use select and map easily.

Ruby
class MyCollection
  include Enumerable

  def initialize(items)
    @items = items
  end

  def each
    @items.each { |item| yield item }
  end
end

collection = MyCollection.new([10, 15, 20, 25, 30])

# Find all numbers greater than 18
big_numbers = collection.select { |num| num > 18 }

# Double each number
doubled = collection.map { |num| num * 2 }

puts "Numbers > 18: #{big_numbers.inspect}"
puts "Doubled numbers: #{doubled.inspect}"
OutputSuccess
Important Notes

Enumerable saves you from writing common loops and checks again and again.

Always define each correctly to get Enumerable's power.

Enumerable methods return new collections or values without changing the original.

Summary

Enumerable gives many useful methods to work with collections.

You only need to define each once to get all Enumerable methods.

This makes your code shorter, clearer, and easier to maintain.