Hash (Dictionary)
Key-value storage, access, and iterating with each.
Simple enough for a 5-year-old to understand
Create and access a Hash
person = { "name" => "Alex", "age" => 36 }puts person["name"]Key-value storage, access, and iterating with each.
Simple enough for a 5-year-old to understand
person = { "name" => "Alex", "age" => 36 }puts person["name"]A Hash is a collection that holds key-value pairs. The difference from an array is that you access elements using a MEANINGFUL key instead of a sequence number. The search operation is fast and independent of the number of elements.
In Ruby, a hash key can be any object, but symbols are used in practice. A symbol is created only once in memory, is immutable, and is fast to compare — these three characteristics make it ideal for being a key.
The most surprising behavior of a hash is accessing a non-existent key: it doesn't throw an error, it returns nil. A misspelled key name silently produces nil, and the error only appears when that nil is used in a method — far away from the root cause.
Hashes are used to hold fields within a record or configuration settings; key names make the code self-explanatory.
If the absence of a key is an error condition, use fetch: it immediately reports the missing key and doesn't propagate nil into the program.
Wrong
user = { name: "Ali", age: 30 }
puts user["name"]The key was defined as a symbol but is being queried with a string; a symbol and a string are NOT the same key. The result is nil and no error message is received, only a blank line is printed. This is the most common hash mistake in Ruby.
Correct
user = { name: "Ali", age: 30 }
puts user[:name]Wrong
settings = { theme: "dark" }
puts settings[:language].upcaseA non-existent key returns nil, then when a method is called on nil, an "undefined method 'upcase' for nil" error occurs. The error appears a step beyond the actual cause. Providing a default value or using fetch solves the problem at the source.
Correct
settings = { theme: "dark" }
puts settings.fetch(:language, "tr").upcaseWrong
counts = Hash.new(0) counts[:a] += 1 other = Hash.new([]) other[:x] << 1 other[:y] << 2 puts other[:x].inspect
When an OBJECT is given as the default value, all keys share the SAME object; adding a minus appears in all of them and both values are printed to the screen. Also, the key is never added to the hash. The block format creates a new object for each key.
Correct
counts = Hash.new(0)
counts[:a] += 1
other = Hash.new { |h, k| h[k] = [] }
other[:x] << 1
other[:y] << 2
puts other[:x].inspectSymbol. It is created once in memory, immutable, and fast to compare. String keys are only needed when reading external data — for example, when parsing JSON, keys come as strings and you may need to convert them.
Yes, Ruby hashes preserve the INSERTION order and this behavior is guaranteed. The difference from an array is that you access by key rather than by position, but when iterating, elements come in the order they were added.
If the absence of a key is normal, square brackets and a nil check are sufficient. If the key must definitely exist, use fetch: if it's missing, it errors immediately and shows the problem at the source, preventing nil from spreading into the program.
A hash holds key-value pairs and access is fast.
A symbol key and a string key are not the same; mixing them up silently produces nil.
A non-existent key returns nil instead of an error.
Passing an object as a default value causes all keys to share it.