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 = gest.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
that we're familiar with Loops and Iteration, let's practice
our knowledge by writing a simple contact list program using Workspaces.
Now we're gonna write a simple contact list program, and
this is what it looks like.
It will ask what the person's name is, and then do we want to add a phone number?
And then, we'll enter a couple phone numbers.
We don't want to add another person, and it will print out the contact list.
So let's go ahead and get started.
Let's go ahead and create a new file and we'll call it contact_list.rb.
So first we will have our contact list be an array and let's set that up, up front.
We now have an empty array.
Now one thing that we're going to be doing a lot is asking the user a question.
Let's go ahead and create a method called ask, since we're going to be asking
questions so often, and we'll call this method ask.
Now let's go ahead and send in a couple arguments.
So we're going to ask a question, and we'll say that the kind
of question we're asking by default is going to be a string.
That's going to be what we want to get back from the user.
So let's go ahead and print the question plus a space,
which will give somebody time to respond.
Now, we will get the answer from standard input, remove any trailing white space,
and then we'll say the answer is going to be an integer
if the kind is a number.
And then we will return the answer.
Now let's just run this, and we'll just say answer equals ask, what is your name.
And since we gave it a kind of string, we don't need to enter that,
since it has what's called a default value of an argument.
And then let's just print out the answer and see what happens.
Okay, so we now know that we are getting back a variable from the ask method.
In our next video, we're going to go ahead and create the add contact method,
which is going to use the ask method which we just wrote.
You need to sign up for Treehouse in order to download course files.Sign up