Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Ruby Loops!
You have completed Ruby Loops!
In this part of building a simple contact list, we're going to add contacts to our `contact_list` array.
Code Samples
We write the following code in this video. A line by line explanation follows:
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
end
answer = ""
while answer != "n"
contact_list.push(add_contact())
end
Code Explanation
First, we create our add_contact method:
def add_contact
We then set up a default contact hash which the method will return. The hash has two keys -- name which is a string and phone_numbers which is an array:
contact = {"name" => "", "phone_numbers" => []}
We then add the name by calling the ask method. The ask method returns a string, which is immediately assigned to the name attribute:
contact["name"] = ask("What is the person's name?")
Next, we set up our answer and loop until the user doesn't want to enter any more phone numbers:
answer = ""
while answer != "n"
answer = ask("Do you want to add a phone number? (y/n)")
If the user answers "y" we ask for a phone number using the ask method. The result is assigned to the phone variable which with then append to the contact["phone_numbers"] array:
if answer == "y"
phone = ask("Enter a phone number:")
contact["phone_numbers"].push(phone)
end
The next lines close the conditional and loop indentation:
end
end
Finally, we set up the answer variable and loop adding contacts until the user is done:
answer = ""
while answer != "n"
contact_list.push(add_contact())
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