Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

MICHAEL P
MICHAEL P
5,191 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

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.

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