Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Collections Build a Grocery List Program Build a Grocery List Program: Part 3

I can't figure out why I am getting this error, Please Help!!

shoppinglist.rb:34:in +': no implicit conversion of nil into String (TypeError) from shoppinglist.rb:34:inblock in print_list' from shoppinglist.rb:33:in each' from shoppinglist.rb:33:inprint_list' from shoppinglist.rb:47:in `<main>'

My code:

def create_list

print "List name: "
name = gets.chomp

hash = {"name" => name, "item" => Array.new}
return hash

end

def add_items

print "Item name: "
item_name = gets.chomp

print "Quantity: "
quantity = gets.chomp.to_i


hash = { "item" => item_name, "quantity" => quantity }
return hash

end

def print_list(list)

puts "List: #{list['name']}"

list["item"].each do |item| puts "Item: " + item['name'] puts "Quantity: " + item['quantity'].to_s

end

end

list = create_list list['item'].push(add_items) print_list(list)

1 Answer

I'm seeing several things why your code may not be working. I think you should use different variable names for the different code blocks so it does not get confusing. Here is my code I had in my workspace

def create_list print "What is the list name? " name = gets.chomp

hash = { "name" => name, "items" => Array.new } return hash end

notice instead of item I have items

so when I use the .each method item is singular not plural

def print_list(list) puts "list: #{list['name']}" print_separator()

list["items"].each do |item| puts "\tItem: " + item['name'] + "\t\t\t" + "Quantity: " + item['quantity'].to_s
end print_separator() end

And then for the Add Item function I have use name in the hash instead of items:

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

Hope that helps!