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 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!