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
Preview
Start a free Courses trial
to watch this video
In this video, we implement searching on the user facing side of things.
Code Samples
when 's'
print "Search term: "
search = gets.chomp
find_by_name(search)
find_by_phone_number(search)
find_by_address(search)
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
Okay, so now that we can add contacts and
print them out, let's go ahead and
0:00
add the ability to search.
0:03
So, first we'll add that as a prompt
on the menu, we'll say Search.
0:07
And this is going to be pretty easy.
0:15
We just add another menu
option in our case statement.
0:18
So when it is the letter s.
0:22
We'll just say enter your search term.
0:27
And then we will grab
that from standard input.
0:33
And now, we've got all of the different
methods that we wrote earlier,
0:37
to find something.
0:43
So we've got, find my name,
find by phone number, and find by address.
0:44
So, since those are already working,
let's go ahead and just call those terms.
0:48
With this search variable that
we just got from standard input.
0:54
And there we go, and actually at the end
of this, okay, we've got a new line.
1:02
Perfect.
1:06
So all we're gonna do,
we get this search query from the user,
1:08
and then we call our methods with it.
1:11
And that's it,
we already wrote the methods earlier.
1:14
So we're just gonna be calling them here.
1:17
Now, we could get more fancy with it and
add each of these as a menu option.
1:19
But I'm just going to assume that when
we want to search our contact list,
1:24
we're gonna look through every field.
1:29
So, now let's go down to the console and
see how it works.
1:30
Now first let's add a contact
to make sure it works.
1:40
Jason Seifer.
1:42
Now add a phone number
to my home phone number.
1:45
123-456-7890.
1:49
And then the other key to go back.
1:52
Add another contact.
1:55
Nick Avery Pettit.
1:56
Now add an address.
2:01
Work address.
2:03
Okay, now let's try searching.
2:13
So, let's try searching for Nick.
2:15
All right, search results for Nick.
2:19
Here's Nick Avery Pettit.
2:21
No phone search results and
no address search results.
2:24
Let's try searching again,
search term is 2.
2:27
And it looks like I came up, Jason Seifer
because my phone number has 2 in it.
2:32
And Nick came up,
because the address has a two in it.
2:39
Okay.
2:42
That's great.
2:43
In our next video,
2:43
we're going to see how to persist
the address book in between sessions.
2:45
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