Enumerable
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: