This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Now that we have our contact list entered, it's time to print out a formatted contact list.
Code Written
We write the following code in the video. An explanation of each line follows.
contact_list.each do |contact|
puts "Name: #{contact["name"]}"
if contact["phone_numbers"].size > 0
contact["phone_numbers"].each do |phone_number|
puts "Phone: #{phone_number}"
end
end
puts "-----\n"
end
Code Explanation
contact_list.each do |contact|
The contact_list
variable is an array. We iterate over each contact using the each
method. The array items are passed in to each iteration of the block as a contact
variable.
puts "Name: #{contact["name"]}"
Each item in the array is a hash. First, we print out the contact's name by accessing the value at the name
key.
if contact["phone_numbers"].size > 0
It is possible to enter a contact without a phone number. The phone_numbers
key is a string which is an array. We check whether or not a contact has any phone numbers by checking whether or not the length
of the phone_numbers
array is greater than 0.
contact["phone_numbers"].each do |phone_number|
puts "Phone: #{phone_number}"
end
Next, we iterate over each phone number and print it out. This only occurs if there are items in the array.
end
puts "-----\n"
end
Finally, we wrap up our loops.
Final Contact List Program
Our final contact list program looks like this:
def ask(question, kind="string")
print question + " "
answer = gets.chomp
answer = answer.to_i if kind == "number"
return answer
end
def add_contact
contact = {"name" => "", "phone_numbers" => []}
contact["name"] = ask("What is the person's name?")
answer = ""
while answer != "n"
answer = ask("Do you want to add a phone number? (y/n)")
if answer == "y"
phone = ask("Enter a phone number:")
contact["phone_numbers"].push(phone)
end
end
return contact
end
contact_list = []
answer = ""
while answer != "n"
contact_list.push(add_contact())
answer = ask("Add another? (y/n)")
end
puts "---"
contact_list.each do |contact|
puts "Name: #{contact["name"]}"
if contact["phone_numbers"].size > 0
contact["phone_numbers"].each do |phone_number|
puts "Phone: #{phone_number}"
end
end
puts "-----\n"
end
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up