Hashes Flashcards
What other data types can we use for hash keys? (apart from symbols)
String, array, integer, float or even another hash. They are bizarre and not really used though.
e.g. {“height” => “6 ft”} (string)
{3.56 => “whatever”} (float)
Initiate a hash called “car” with 3 elements.
car = {ford: “focus,
honda: “civic”,
toyota: “corolla”
}
What a hash is?
A hash is a data structure that stores items by associated keys.
Key-value pairs.
Delete the second element from the hash below!
currency = {yen: “¥”, euro: “€”, dollar: “$”}
currency.delete(:euro)
How do you access the third element of the hash below?
currency = {yen: “¥”, euro: “€”, dollar: “$”}
currency[:dollar]
Merge the two hashes below to return a new merged hash!
currency = {yen: "¥", euro: "€", dollar: "$"} ball= {basketball: "orange", tennis: "yellow"}
currency.merge!(ball)
=> {yen: “¥”, euro: “€”, dollar: “$”, basketball: “orange”, tennis: “yellow”}
Iterate through the hash below and print the results!
currency = {yen: “¥”, euro: “€”, dollar: “$”}
currency.each do |key, val|
puts “The symbol of #{key} is #{val}.”
end
The symbol of yen is ¥.
The symbol of euro is €.
The symbol of dollar is $.
When would you choose to use hash over array?
When data need to be associated with a specific label.
When would you choose to use array over hash?
When order matters.
When I need a “stack” or a “queue” structure.
Use a hash to accept optional parameters when creating methods!
def greeting(name, option = {}) if options.empty? puts "hi my name is #{name}" else puts "hi my name is #{name} and I'm #{options[:age]}" + " years old and I live in #{options[:city]}." end end
greeting(“Tim”)
=>hi my name is Tim
greeting(“Tim”, age: 53, city: “Boston”)
=>hi my name is Tim and I’m 53 years old and live in Boston.
What do you use the “has_key?” method for?
It allows you to check if a hash contains a specific key. It returns a boolean value.
e.g.
currency = {yen: “¥”, euro: “€”, dollar: “$”}
currency.has_key?(“euro”)
=>true
has_value? works exactly the same way.
Which method allows you to pass a block and will return any key-value pairs that evaluate to true when ran through the block?
“select”
e.g.
currency = {yen: “¥”, euro: “€”, dollar: “$”}
currency.select {|k, v| k== “yen” || v == “$” }
=> {yen: “¥”, dollar: “$”}
Which method allows you to pass a given key and it will return the value for that key if it exists?
“fetch”
e.g.
currency = {yen: “¥”, euro: “€”, dollar: “$”}
currency.fetch(“yen”)
=> “¥”
What does the “to_a” method do?
It returns an array version of your hash when called.
e.g.
currency = {yen: “¥”, euro: “€”, dollar: “$”}
currency.to_a
=>[[:yen, “¥”], [:euro, “€”], [:dollar, “$”]]
It doesn’t mutate the caller.
How can you retrieve all the keys or values out of a hash?
With “keys” and “values” methods.
e.g. currency = {yen: "¥", euro: "€", dollar: "$"} currency.keys =>[:yen, :euro, :dollar] currency.values =>["¥", "€", "$"]