Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Part 1: Asking Questions3:10 with Jason Seifer
Now that we're familiar with loops and iteration, let's practice our knowledge by writing a simple contact list program.
Here is the code we write in this portion of the video.
First, we set up a contact list array:
contact_list = 
Next, we define the
ask method. We're going to be asking the user for input quite a bit so the
ask method will repeat the logic for us.
def ask(question, kind="string") print question + " " answer = gets.chomp answer = answer.to_i if kind == "number" return answer end
ask method takes two arguments and defaults to having the
kind of answer be a string. This will let us return numeric values if we want.
Finally, we test the
answer = ask("What is your name?") puts answer
[SOUND] Now 0:00 that we're familiar with Loops and Iteration, let's practice 0:04 our knowledge by writing a simple contact list program using Workspaces. 0:08 Now we're gonna write a simple contact list program, and 0:13 this is what it looks like. 0:17 It will ask what the person's name is, and then do we want to add a phone number? 0:18 And then, we'll enter a couple phone numbers. 0:31 We don't want to add another person, and it will print out the contact list. 0:34 So let's go ahead and get started. 0:40 Let's go ahead and create a new file and we'll call it contact_list.rb. 0:44 So first we will have our contact list be an array and let's set that up, up front. 0:55 We now have an empty array. 1:04 Now one thing that we're going to be doing a lot is asking the user a question. 1:07 Let's go ahead and create a method called ask, since we're going to be asking 1:11 questions so often, and we'll call this method ask. 1:15 Now let's go ahead and send in a couple arguments. 1:25 So we're going to ask a question, and we'll say that the kind 1:30 of question we're asking by default is going to be a string. 1:37 That's going to be what we want to get back from the user. 1:42 So let's go ahead and print the question plus a space, 1:45 which will give somebody time to respond. 1:51 Now, we will get the answer from standard input, remove any trailing white space, 1:56 and then we'll say the answer is going to be an integer 2:05 if the kind is a number. 2:11 And then we will return the answer. 2:18 Now let's just run this, and we'll just say answer equals ask, what is your name. 2:23 And since we gave it a kind of string, we don't need to enter that, 2:34 since it has what's called a default value of an argument. 2:40 And then let's just print out the answer and see what happens. 2:46 Okay, so we now know that we are getting back a variable from the ask method. 2:52 In our next video, we're going to go ahead and create the add contact method, 3:01 which is going to use the ask method which we just wrote. 3:07
You need to sign up for Treehouse in order to download course files.Sign up