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 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,503 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,503 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.