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

Enumerable

In this page:

  1. Enumerable

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
🔒

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.