Hash.new


#1

I am wondering if I have this set up correctly. The error asks me if I declared a variable called pets.

pets = Hash.new
cat_1= "Francis" ,
cat_2= "Quarterpint",
cat_3= "Walela",
cat_4= "Hobo",
cat_5= "Misty",
cat_6= "Luna",
cat_7= "Pocket",


#2

Don't know which exercise it is, but I think they're asking your to fill the hash no?


#3

Hi,

I don't understand if you want to add or call hash objects.

You can create hashes two ways first one is explained in 6. Introduction to Hashes in Data Structures.

The first one is like this:

hash = {
  key1 => value1,
  key2 => value2,
  key3 => value3
}

And the second one is explained in 7. Using Hash.new in Data Structures.You should first create an Hash and then add the keys and values.

First we create an Hash in the variable pets, like this:

pets = Hash.new

And then we add keys and values to the hash like this:

pets["Stevie"] = "cat"
# Adds the key "Stevie" with the
# value "cat" to the hash

This is also explained in 8. Adding to a Hash in Data Structures

And for accessing the hash that is explained in Accessing Hash Values: 9. Accessing Hash Values

Use code like this:

puts pets["Stevie"]
# will print "cat"

#4

Thank you for replying, guys... I wasn't using the correct format, so Ruby couldn't understand it (of course!). But I have since used the right format and went on through.


#5

Try this one its working

pets = Hash.new
{
"cat_1" => "Francis" ,
"cat_2" => "Quarterpint",
"cat_3" => "Walela",
"cat_4" => "Hobo"

}