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

Oğulcan Girginc
Oğulcan Girginc
24,848 Points

undefined method `push' for nil:NilClass (NoMethod Error)

def create_list
  print "What is the list name?: "
  name = gets.chomp

  hash = { name: name, items: Array.new }
  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())

puts list.inspect

When I use

hash = { name: name, items: Array.new }

instead of

hash = { name: name, "items" => Array.new }

I am getting an error. Does anyone know why?

3 Answers

Martin Cornejo Saavedra
Martin Cornejo Saavedra
18,132 Points

The error is here:

list['items'].push(add_list_item())

#Should be
list[:items].push(add_list_item())
Oğulcan Girginc
Oğulcan Girginc
24,848 Points

So if I want to use

name: item_name

I always need to use

list[:name]

Am I correct?

Alan Matthews
Alan Matthews
10,161 Points

I believe it would depend upon on what the hash key is. In your above code you made hash = { name: name, items: Array.new } a hash, where items: is a symbol that is the key and a new Array is the value. Newer versions of Ruby are deprecating the old hash syntax in favor of using symbols as keys. Docs here: http://rubylearning.com/satishtalim/ruby_hashes.html

If you had made items a string in the create_list method, then your original syntax list['items'].push(add_list_item()) should work if I'm not mistaken.

Alan Matthews
Alan Matthews
10,161 Points

You also don't need to specifically return anything in a Ruby method. It will always return the last expression evaluated.