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 Create a Method That Returns a Hash

Tobias Jackson
Tobias Jackson
9,758 Points

Create a method named "create_shopping_list" that returns a hash. It does not need to ask for a name or get anything fro

I can't figure out what wrong with my code.

shopping_list.rb
def create_shopping_list 
  hash =  { "name" => name }
  return hash
end

1 Answer

andren
andren
28,558 Points

The problem is the value of the hash:

{ "name" => name }

You set a key called name to a variable called name, but that variable does not exist. That's what causes an error.

You can solve the issue by simply having a string as the key like this:

def create_shopping_list 
  hash =  { "name" => "Tobias" }
  return hash
end

The questions is misleading when it says it does not need to ask for a name, but in order to proceed you have to setup a hash with a name. Wouldn't the question make more sense to say "create a hash with a key of name and value of your name".

I tried forever to create an empty hash with hash.new() and it didn't like that.

andren
andren
28,558 Points

You don't actually need to have a name key in the hash, the challenge accepts an entirely empty hash as well:

def create_shopping_list
  return {}
end

The only reason I placed a name key in the hash in my solution was because I was correcting Tobias's existing code.