03/19 Questions about hashes


#1



creatures = { "weasels" => 0,
  "puppies" => 6,
  "platypuses" => 3,
  "canaries" => 1,
  "Heffalumps" => 7,
  "Tiggers" => 1
}

puts creatures[0]

I know that this lesson isn't asking for this but just for my own knowledge, I would be able to put weasels key onto the screen by using the element number like I did above, is this correct? If not how would I be able to print weasels onto the screen? Or would I have to do something like i did below in order to print the key? I tried doing it in the codecademy console but it gave me errors.

creatures.each do |key, val|
puts creatures[val]
end


#2

Keys aren't numbered, you can use keys to find their corresponding values.

If you want to find things by index, use an array.

If you want to iterate through the keys of a hash, then you would call the hash's keys method which returns an array which you can iterate through


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.