6/19, Oops, try again. It looks like you didn't print out the value of each of the keys stored in your hash


#1

pets = Hash.new
pets["dog"] = 5
pets["cat"] = 6

puts pets["dog"]
puts pets["cat"]

puts pets[0]
puts pets[1]

I do followed the instruction, puts the value, but it cannot pass.


#2

well, changed to this and passed:

pets = Hash.new
pets["cat"] = "hahaha"

puts pets["cat"]

so it must be a string and single element in the hash? seems a bug to me :frowning:


#3

No, a hash can take anything as a key or as a value, but the problem you had in your first code was that you asked puts to use pets with the keys "0" and "1", even though there's nothing at those keys since you only filled the hash with the keys "dog" and "cat" (respectively with "5" and "6").


#4

Hi, thanks for your reply.
The pets[0] & pets[1] was my third trying, which at first I tried just pets["dog"] & pets["cat"].
Well, thank you again for the heads up. I thought maybe can use pets[0] to access 5, and pets[1] to 6, now it seems that's not right.


#5

If you use 0 and 1 to access something (in a hash), it means that you used those keys to insert this something in the first place.

For arrays, it's different, because the "keys" or "index" are always integers starting from 0, so you don't need to specify them when you add data, which means that you don't have to bother about keys at all. I think that's what you're confused about.


#6

This didn't pass:

pets = {
"One" => 1,
"Two" => 2,
"Three" => 3
}

puts pets["One"]
puts pets["Two"]
puts pets["Three"]

This did:

pets = {
"One" => "Hello",
"Two" => "Hi",
"Three" => "There"
}

puts pets["One"]
puts pets["Two"]
puts pets["Three"]

Why?