×

ruby · level 3 · unit 2 · lesson 4

  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

With no block, each should hand back an .

Call an array's each with no block and you get an enumerator: an object that remembers its place, like a bookmark. Ask it for .next and it hands out one item, then waits. Or chain it, as in each.with_index(1), to add a counter that starts at 1.

Your own each should behave the same way. Start it with and Ruby builds the enumerator for you. When next runs out of items it raises , and loop do treats that as a polite signal to stop.

class Playlist
  def initialize(songs)
    @songs = songs
  end
  def each
    return to_enum(:each) unless block_given?
    @songs.each { |song| yield song }
  end
end
songs = Playlist.new(["Africa", "Mr Blue Sky", "Toxic"])
player = songs.each
puts player.next
puts player.next
songs.each.with_index(1) { |song, place| puts "#{place}. #{song}" }

unless is Ruby's if not, and loop do ... end repeats its block until something stops it.