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
- String keys use
=>; assignment adds new pairs in place. fetchtakes a fallback;Hash.new(0)makes counters one-liners.eachyields key and value together;keys.sortlists them.
Keywords and builtins used here
puts
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.
Step 2 of 3 in Collections, step 5 of 29 in Language basics.