ruby · level 3 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The queue runs dry. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
queue = ["Ana", "Ben", "Cy"].each
loop do
puts "Serving #{queue.next}"
end
puts "Queue empty"
your turn
Your turn. Number the steps of a recipe.
Make each return an enumerator when there is no block, add a last step of your own, then make the numbering start at 1.
fix it
The leaderboard cannot number its players. Fix each.
board.eachis called with no block. What doesyielddo when there is no block?- With no block,
eachshould hand back an enumerator instead of yielding. - Add
return to_enum(:each) unless block_given?as the first line insideeach.
nailed it
you made enumerators hand out items. :D
- With no block,
eachshould returnto_enum(:each). nexthands out one item and raises StopIteration at the end.with_index(1)numbers items starting from 1.
new words in your collection
- enumerator
- to_enum
- StopIteration
This lesson isn’t saved. A free account remembers every lesson you finish.