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 trialMICHAEL P
5,191 PointsKeep 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
57,712 PointsHi 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.
MICHAEL P
5,191 PointsThank you Steve.
MICHAEL P
5,191 PointsIt makes sense.
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsI added a couple of comments in your code to show you what I'm on about!