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:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Including
Enumerablewithout definingeach, so none of the methods work. - Using
returnvalues instead ofyieldineach, somapandselectreceive nothing. - 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: