Hashes Flashcards
How do you create a new hash called my_hash using the literal constructor?
my_hash = { }
How do you create a new hash called my_hash using the class constructor?
my_hash = Hash.new
How would you retrieve the value “Pluto” in the following hash?
pets = {“cat” => “Maru”, “dog” => “Pluto”}
pets[“dog”]
How would you add the key and value pair, “bird” and “Sammy in the following hash?
pets = {“cat” => “Maru”, “dog” => “Pluto”}
pets[“bird”] = “Sammy”
How would you reassign the value of the key “dog” from “Pluto” to “Koikoi” in the following hash?
pets = {“cat” => “Maru”, “dog” => “Pluto”}
pets[“dog”] = “Koikoi”
What does a symbol look like?
:this_is_what_a_symbol_looks_like
Symbols start with a colon.
What is the difference between a string and a symbol?
Strings are mutable while symbols are not. Symbols cannot be modified after being created and will always stay the same size in memory.
How do you express the symbol :instructor with a value of “Isaac Newton” in a hash?
{ instructor: “Isaac Newton” }
How do you iterate over a hash using an each method?
hash.each do |key, value| #your code here end
What would the following code look like?
hash = {key1: “value1”, key2: “value2”}
hash.each do |key, value|
puts “#{key}: #{value}”
end
“key1: value1”
“key2: value2”
What value will the following code return?
birthday_kids = { "Timmy" => 9, "Sarah" => 6, "Amanda" => 27 }
birthday_kids.collect do |kids_name, age|
age * 7
end
[63, 42, 189]
How would you retrieve the string “Jasmine” in the following hash?
school = {
instructors: [“Cadence”, “Melody”, “Lryic”],
dev_team: [“Rose”, “Lily”, “Violet”, “Jasmine”],
students: [“Shelly”, “you”, “Sandy”, “Rocky”]
}
school[:dev_team][3]
How would you retrieve the string “you” in the following hash?
school = {
instructors: [“Cadence”, “Melody”, “Lyric”],
dev_team: [“Rose”, “Lily”, “Violet”, “Jasmine”],
students: [“Shelly”, “you”, “Sandy”, “Rocky”]
}
school[:students][1]
What value will the following code return?
groceries = {fruit: “Banana”, vegetable: “Broccoli”, dessert: “Cookie”}
groceries.values
[“Banana”, “Broccoli”, “Cookie”]
What value will the following code return?
groceries = {fruit: “Banana”, vegetable: “Broccoli”, dessert: “Cookie”}
groceries.keys
[:fruit, :vegetable, :dessert]