ruby · level 3 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
This each is choosy. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Library
def initialize(books)
@books = books
end
def each
@books.each do |title, on_loan|
yield title if !on_loan
end
end
end
library = Library.new({ "Dune" => false, "Emma" => true, "Holes" => false })
library.each { |title| puts title }
your turn
Your turn. Let people loop over a recipe.
In the first blank, make each hand every ingredient to the caller's block. Add a fourth ingredient of your choice in the second blank.
fix it
Everyone is ready, but nobody has a name. Fix it.
- Every line says is ready, but with no name. What does the caller's block receive?
yieldon its own hands the block nothing, soplayerisnilinside it.- On line 6, change
yieldtoyield player, then press run.
nailed it
your class can be looped over now. :D
- Keep the array private and give the class an
each. eachyields every item to the caller's block.- Your
eachdecides which items callers see, and in what order.
new words in your collection
- iterate
- collection
This lesson isn’t saved. A free account remembers every lesson you finish.