×

ruby · level 3 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Give your own class an each, and people can loop over it.

A playlist could be a plain array, but then any part of the program can reach in and mess it up. Professionals wrap the array in a class and keep it private. To let others , going through the items one by one, give the class an each method that yields every item.

Inside, each borrows the array's own each and passes each song on with yield. From outside, your playlist now behaves like any : road_trip.each do |song| reads the same as looping over an array, but nobody can touch @songs directly.

class Playlist
  def initialize(songs)
    @songs = songs
  end
  def each
    @songs.each { |song| yield song }
  end
end
road_trip = Playlist.new(["Africa", "Mr Blue Sky", "Toxic"])
road_trip.each do |song|
  puts "Now playing: #{song}"
end

Your each decides what callers see and in which order, because the block only runs when you yield.