Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
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 modify our program to output our list for us.
Code Samples
At the end of the video, your code should look like this:
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
print "How much? "
quantity = gets.chomp.to_i
hash = { "name" => item_name, "quantity" => quantity }
return hash
end
def print_list(list)
puts "List: #{list['name']}"
puts "----"
list["items"].each do |item|
puts "Item: " + item['name']
puts "Quantity: " + item['quantity'].to_s
puts "---"
end
end
list = create_list()
puts list.inspect
list['items'].push(add_list_item())
puts list.inspect
print_list(list)
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