typestar

Hashes in Ruby

Key-value pairs with defaults, fetch fallbacks and easy iteration.

stock = { "apples" => 12, "pears" => 4 }
stock["plums"] = 9
puts stock["apples"]
puts stock.fetch("kiwis", 0)

# a default value means missing keys start at zero instead of nil
tally = Hash.new(0)
tally["ada"] += 1
tally["ada"] += 1
puts tally.inspect

stock.each { |fruit, count| puts "#{fruit}: #{count}" }
puts stock.keys.sort.inspect

How it works

  1. String keys use =>; assignment adds new pairs in place.
  2. fetch takes a fallback; Hash.new(0) makes counters one-liners.
  3. each yields key and value together; keys.sort lists them.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
337
Tokens
100
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 2 of 3 in Collections, step 5 of 29 in Language basics.

← Previous Next →