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

MICHAEL P
MICHAEL P
5,190 Points

Keep Getting "Undefined method 'push' for nil: NilClass error" - Not Sure Why?

I keep getting the error message "Undefined method 'push' for Nil: NilClass error" - Not sure why.

Workspaces keeps stating to me that the error occurs on line 22.

Can someone please let me know what the heck I am doing wrong? I am going to include the code that I have so far.

Also I am running OS X:

def create_list
  print "What is the list name? "
  name = gets.chomp
  hash = { "name" => name, "Items" => Array.new } # called "Items" here
  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

list = create_list()
puts list.inspect
list['items'].push(add_list_item())  # but called 'items' here

puts list.inspect
puts add_list_item().inspect

[MOD: edited code block. sh]

3 Answers

Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 57,627 Points

Hi Michael,

THis is because items doesn't exist; it is a NilClass instance.

When you've created the array inside of create_list you've called it Items (capital 'I'); later, at the push you've used the key items which isn't the same thing. I suggest you lowercase the I at line 4 to be "items" => Array.new. That should work for you.

Make sense?

Steve.

Steve Hunter
Steve Hunter
Treehouse Moderator 57,627 Points

I added a couple of comments in your code to show you what I'm on about!