Lesson 5 of 8 · 9 min

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

  1. word_counts(text): how many times each lower-case word appears.
  2. by_city(people): given hashes with :name and :city, a hash from each city to the list of names there.
  3. price_list(prices): given { bread: 1.5 }, the list ["bread: $1.50"].
main.rb
def word_counts(text)
end

def by_city(people)
end

def price_list(prices)
end

p word_counts("to be or not to be")

Ruby 3.4 runs right here in your browser. The first run downloads about 16 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…