Hashes
| Hash literals | |
| Read and fetch | |
| Keys values each | |
| Default values |
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]
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)
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
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
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.
Next: Ranges
Article author: Arthur Isaev