Hashes

Hash literals

Curly braces group key value pairs into a hash. Symbols written with a trailing colon are the usual keys: short, readable labels for each value. Values may be of any type, mixed freely in one hash.

user = { name: "Ada", age: 36 } puts user[:name] puts user[:age]

ruby user.rb

Ada
36

Read and fetch

Brackets return nil for a missing key, which is quiet but easy to overlook. The method fetch is stricter: it raises a KeyError for a missing key unless you pass a fallback value. The predicate key? simply reports whether a key is present.

user = { name: "Ada", age: 36 } puts user.fetch(:age) puts user.fetch(:city, "unknown") puts user.key?(:city)

ruby fetch.rb

36
unknown
false

Keys values each

The methods keys and values return plain arrays of each side. The method each yields the key and the value together into two block variables. The method length counts the stored pairs.

user = { name: "Ada", age: 36 } puts user.keys.length user.each do |key, value| puts "#{key}: #{value}" end

ruby each.rb

2
name: Ada
age: 36

Default values

A plain hash answers nil for unknown keys. Passing a default to Hash.new changes that answer, which makes counters tidy. For a default that must stay fresh per key, such as an empty array, use the block form so every key receives its own object.

counts = Hash.new(0) counts["Ada"] += 1 puts counts["Ada"] puts counts["Bob"] lists = Hash.new { |h, k| h[k] = [] } lists["a"].push(1) puts lists["a"].length

ruby defaults.rb

1
0
1

The unknown name scores 0 without ever being stored. The block form stores a fresh array for key a, so its length is 1.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How is a hash with symbol keys written?

    Answer

    {name: "Ada"}

    Braces group the pairs, and the trailing colon after name makes the symbol key.

  2. What does this program print? user = { name: "Ada", age: 36 } puts user[:name]

    Answer

    Ada

    The symbol key :name holds the string, and puts prints it without quotes.

  3. What does user[:city] return when the key is absent?

    Answer

    nil

    Brackets are quiet about a missing key, which is why fetch exists.

  4. What does user.fetch(:city) do when the key is absent?

    Answer

    Raises KeyError

    fetch without a fallback raises, while fetch(:city, "unknown") returns the fallback.

  5. What does this program print? user = { name: "Ada", age: 36 } puts user.fetch(:city, "unknown")

    Answer

    "unknown"

    The second argument is the fallback, and puts prints it without quotes.

  6. What does user.key?(:city) return for that hash?

    Answer

    false

    The predicate reports whether the key is present, and city is not.

  7. What does this program print? user = { name: "Ada", age: 36 } puts user.keys.length

    Answer

    2

    keys returns the two symbols, so its length is 2.

  8. What does this program print? counts = Hash.new(0) counts["Ada"] += 1 puts counts["Bob"]

    Answer

    0

    The default 0 answers for an unknown key without storing it.

  9. Why does the lesson use Hash.new { |h, k| h[k] = [] } for lists?

    Answer

    So every key receives its own array instead of one shared object

    A shared default array would collect the values of every key into one list.

  10. Which method yields a key and its value together?

    Answer

    each

    Hash#each passes the pair into two block variables.

Article author: Arthur Isaev