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
Now that we know how to use arrays and hashes, we're going to build a small program that makes a grocery list for us. In this video, we'll add methods to create our list and also add items to it.
Code Samples
Here is the code we write in the video. Follow along using Workspaces!
def create_list
print "What is the list name? "
name = gets.chomp
hash = { "name" => name, "items" => Array.new }
return hash
end
def add_list_item
print "What is the item called?"
item_name = gets.chomp
hash = { "name" => name }
return hash
end
list = create_list()
puts list.inspect
[SOUND] Now that we know how
to use arrays and hashes,
0:00
let's write a simple program that
uses everything we've used so far.
0:05
We're going to do this over
a few different videos, so
0:12
be sure to follow along using workspaces.
0:15
Okay, now that we know how to work with
arrays and hashes, let's go ahead and
0:18
write a simple shopping list program.
0:23
So I've gone ahead and
launched a new Ruby workspace.
0:26
Now, let's go ahead and create a new file.
0:30
And we'll call this shopping list.rb.
0:33
Now let's go ahead and
create a shopping list.
0:38
We'll create a method that asks for
the name of the list, and then,
0:42
we can return a hash of the name and
the items inside of the shopping list.
0:46
So we'll call that method, create list.
0:54
Now let's go ahead and
ask what the list's name is.
1:00
And we will take from standard input,
the name of the shopping list and
1:08
remove any external characters from
it that are white space at the end.
1:13
Now let's go ahead and return a new hash.
1:19
We will give the hash a key of name and
a key of items.
1:26
Which is a new array.
1:34
And then, we'll go ahead and
return this hash.
1:36
Now that we have a method to create
the list, let's go ahead and
1:42
create a method to add
an item to the list.
1:46
So now we're going to add a list item, and
2:01
we'll get the item name
from standard input.
2:03
And then we'll create a new hash,
and we can return that hash.
2:08
Go ahead and save that.
2:15
And now, let's go ahead and ask the user.
2:17
Or their list.
2:21
So we can say, list and
then an equals sign, and
2:23
we'll call the method create list.
2:28
Now what that will do is ask the user for
the name of the shopping list,
2:34
and return a hash with the key of name and
the key of items, which is an array.
2:39
And let's go ahead and
print out list.inspect.
2:48
Now let's click down in the console and
run this shopping list program.
2:53
The list name is groceries.
2:58
Now we can see we've got this list hash,
3:01
with the name of what we input
in an empty array for items.
3:05
In the next video,
we'll start adding items to the list.
3:11
You need to sign up for Treehouse in order to download course files.
Sign up