Hashes and symbols
A hash stores values under keys:
capitals = { "Zimbabwe" => "Harare", "Kenya" => "Nairobi" }
capitals["Zimbabwe"] # "Harare"
capitals["Ghana"] = "Accra" # add or change
capitals.key?("Kenya") # true
capitals.fetch("France", "?") # "?" when the key is missing
Symbols
Keys are very often symbols: names that start with a colon, like :name. They are lightweight, fixed labels. Hashes with symbol keys have a short syntax:
person = { name: "Ana", city: "Harare" } # the same as { :name => "Ana", :city => "Harare" }
person[:city] # "Harare"
Looping and transforming
person.each { |key, value| puts "#{key}: #{value}" }
person.map { |key, value| "#{key}=#{value}" } # an array of strings
Counting and grouping
%w[a b a c a].tally # {"a"=>3, "b"=>1, "c"=>1}
counts = Hash.new(0) # missing keys start at 0
"banana".each_char { |c| counts[c] += 1 }
[1, 2, 3, 4].group_by(&:even?) # {false=>[1, 3], true=>[2, 4]}
{ a: 1, b: 2 }.transform_values { |v| v * 10 } # {a: 10, b: 20}
format("%.2f", 1.5) gives "1.50".
Your task
word_counts(text): how many times each lower-case word appears.by_city(people): given hashes with:nameand:city, a hash from each city to the list of names there.price_list(prices): given{ bread: 1.5 }, the list["bread: $1.50"].