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
endgreeting(“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
=>["¥", "€", "$"]Write a program that prints out groups of words that are anagrams.
words = [‘demo’, ‘none’, ‘tied’, ‘evil’, ‘dome’, ‘mode’, ‘live’, ‘fowl’, ‘veil’, ‘wolf’, ‘diet’, ‘vile’, ‘edit’, ‘tide’, ‘flow’, ‘neon’]
result = {}
words.each do |word|
key = word.split('').sort.join
if result.has_key?(key)
result[key].push(word)
else
result[key] = [word]
end
endresult.each_value do |v|
puts “——”
p v
end
Use Ruby’s built-in select method to gather only immediate family members’ names into a new array.
family = { uncles: [“bob”, “joe”, “steve”],
sisters: ["jane", "jill", "beth"],
brothers: ["frank","rob","david"],
aunts: ["mary","sally","susan"]immediate_family = family.select do |k, v|
k == :sisters || k == :brothers
end
arr = immediate_family.values.flatten
p arr
What is the difference between the array#each and hash#each methods?
With array#each there is one block parameter, but with hash#each there are two.
e. g.
numbers. each {|number| number * 2}
numbers.each {|key, val| val * 2}
What is the differenae between Enumerator#map and Array#map?
Enumerable#map can accept two block parameters instead of one (key,val).
However, Enumerable#map doesn’t returns a hash when invoked on a hash, but it returns an array.
e.g.
numbers = {high:100, medium:50, low:10}
half_numbers = numbers.map do |key,val|
val / 2
endp half_numbers
=> [50,25,5]
How to nest the following two hashes?
drinks = {
pepsi: "cola",
juice: "orange",
tea: "lemon"
}
food = {
pizza: "salami",
burger: "McDonalds",
pasta: "spagetti"
}mix = {
drinks: {pepsi: “cola”, juice: “orange”, tea: “lemon”},
food: {pizza: “salami”, burger: “McDonalds”,pasta: “spagetti”}
}
=> {
:drinks=> {:pepsi=> “cola”, :juice=> “orange”, :tea=> “lemon”},
:food=> {:pizza=> “salami”, :burger=> “McDonalds”,:pasta=> “spagetti”}
}
Turn this hash into an array containing only Barney’s name and number!
flintstones = {“Fred” => 0, “Wilma” => 1, “Barney” => 2, “Betty” => 3, “BamBam” => 4, “Pebbles” => 5}
flintstones.assoc(“Barney”)
=>[“Barney”, 2]
Hash#assoc searches through the hash, comparing obj with the key. It returns the key-value pair (two elements array) or nil.
flintstones. slice(“Barney”).to_a.flatten
flintstones. keep_if{|key,val| key == “Barney”}.to_a.flatten