← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 4 of 6

Enumerable

Enumerable gives a class a whole set of list tools like map and select, as long as it knows how to go through its items one by one. It is like handing a kit of helpers to anything that can be walked through.

In this page:

  1. Enumerable
Syntax
ruby
class ClassName
  include Enumerable

  def each
    # yield each element
  end
end

Enumerable

Mixing in Enumerable gives a class methods like .map, .select, .sort, .include?, and dozens more, as long as the class defines a single each method describing how to iterate its elements.

This is exactly how Array and Hash get so many shared collection methods. It's a powerful example of Ruby's "provide one method, get many for free" module design.

Note: Implementing just each and including Enumerable unlocks dozens of collection methods automatically -- one of Ruby's best examples of mixin power.

Example: Enumerable

markup
class Playlist
  include Enumerable

  def initialize(songs)
    @songs = songs
  end

  def each
    @songs.each { |song| yield song }
  end
end

playlist = Playlist.new(["Song A", "Song B", "Song C"])

puts playlist.map { |s| s.upcase }.inspect
puts playlist.include?("Song B")
puts playlist.sort.inspect
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Including Enumerable without defining each, so none of the methods work.
  2. Using return values instead of yield in each, so map and select receive nothing.
  3. Expecting Enumerable methods to work like arrays, such as playlist[0], when it gives only iteration methods.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.