Hashes – lookup tables
A hash maps keys to values, like a little dictionary. Keys like :name are symbols – lightweight names with a colon.
animal = { name: "Chunky", food: "bacon" }
animal[:name]Also try animal[:food] – or a key that doesn't exist: then you get nil.
A hash can be changed at any time: animal[:age] = 3 adds a new entry, and the same notation overwrites an existing one. each walks through all pairs – the block gets the key and the value:
animal[:age] = 3
animal[:food] = "even more bacon"
animal.each do |key, value|
puts "#{key}: #{value}"
endA few useful hash methods. fetch is the strict sister of []: if the key doesn't exist, it takes the fallback value you hand it (without a fallback it reports an error – often better than a silent nil):
p animal.keys # all keys
p animal.values # all values
p animal.key?(:name) # is the key there?
p animal.length # how many pairs?
animal.fetch(:color, "orange")Symbols like :name are popular keys because they are short and fast: the same symbol is always the very same object. But keys may be anything – often they are strings, for example in data from the internet (lesson 63). Then you write an arrow => between key and value:
prices = { "bacon" => 4.5, "egg" => 1.2, "coffee" => 3.0 }
puts prices["egg"]
p prices[:egg] # careful: a symbol is not a string!prices[:egg] gives nil, because the key is "egg", not :egg – a classic stumbling block.
To finish, a classic: counting things. Hash.new(0) builds a hash that answers 0 instead of nil for missing keys. That way you can simply count up without checking first whether the key already exists:
counter = Hash.new(0)
"chunky bacon".delete(" ").each_char do |letter|
counter[letter] += 1
end
counterdup only copies the top level. If the hash holds an array, the original and the copy share that array:
kaz = { name: "Kaz", likes: ["bacon"] }
copy = kaz.dup
copy[:name] = "Isi" # a new string: only copy changes
copy[:likes] << "toast" # the shared array: both change
show_objects(kaz: kaz, copy: copy)kaz[:name] is still "Kaz", but kaz[:likes] has toast in it now too.
fox with the keys :name and :food (pick any values). Then add the age with fox[:age] = … – a number.# fox = { ... }
words: tally is a hash from word to count – like the counter with Hash.new(0) above. Then find in most_common the word that occurs most: tally.values.max is the largest count, and tally.key(…) gives the key for a value.words = %w[bacon egg bacon toast egg bacon]
# tally = ... # word => how often it occurs
# most_common = ... # the word that occurs most