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

Sean Flanagan
Sean Flanagan
33,235 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" => Array.new }
  return hash
end

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
end

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 "---"
  end
end

list = create_list()
puts list.inspect
list['items'].push(add_list_item())

puts list.inspect

print_list(list)

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,340 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,235 Points

Sorted! Thanks Joseph! :-)