tnaught tnaught - 4 months ago 5x
Ruby Question

Creating a Hash with a method

I am having trouble creating a method to establish a new hash. I know that it is definitely easier just to declare the hash, however I need to create a method. Here is what I have so far and it keeps generating an error message.

def create_new(hash_name)
hash_name =


This should create and empty hash^

def add_item(hash_name, item_name, item_quantity)

hash_name[:item_name.to_sym] = item_quantity

I keep getting an error message on the above code^ I am trying to update this hash and add a new key value pair with a method

p create_new("grocery_list")

This creates a new empty hash^ however when I call it with the below code is says the hash is undefined

add_item(grocery_list, "pizza", "1")
p grocery_list


in your create_new method, you define a hash_name local variable. This variable does not exist anywhere but the body of your method. That's what seems to confuse you.

You could express better your intent with :

def create_new

def add_item(hash, key, value)
   hash[key.to_sym] = value

In order to get to what you are trying to do, you will have to store the result of your method in some kind of variable in order to use it :

grocery_list = create_new('unused variable') # grocery_list is now a local variable

add_item(grocery_list, 'pizza', 1)