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

Sean Flanagan
Sean Flanagan
33,223 Points

"Undefined method" error message

Hi. Can anyone please tell me where I've gone wrong?

Here's my syntax:

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

  hash = { "name" => name, "items" => }
  return hash

def add_list_item
  print "What's the item called? "
  item_name = gets.chomp

  print "How much? "
  quantity = gets.chomp.to_i

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

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

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

list = create_list()
puts list.inspect

puts list.inspect


And the error:

What's the list's name? Groceries                                                           
{"name"=>"Groceries", "items"=>[]}                                                          
What's the item called? Milk                                                                
How much? 1                                                                                 
{"name"=>"Groceries", "items"=>[{"name"=>"Milk", "quantity"=>1}]}                           
List: Groceries                                                                             
shopping_list.rb:24:in `print_list': undefined method `each' for nil:NilClass (NoMethodError
        from shopping_list.rb:37:in `<main>'  

Thanks in advance for any assistance. :-)

1 Answer

Joseph Kato
Joseph Kato
35,335 Points

Hi Sean,

It appears that in your print_list method you've written list["item"].each when you meant list["items"].each.

Sean Flanagan
Sean Flanagan
33,223 Points

Sorted! Thanks Joseph! :-)