Hashes in Ruby
Store and retrieve key-value pairs using Ruby hashes, including symbols as keys, merging, and iteration.
Introduction to Hashes
A Hash is a collection of key-value pairs. Keys are unique — setting the same key twice overwrites the value. Ruby hashes maintain insertion order.
1. What Is a Hash?
Hashes map unique keys to values. Keys and values can be any Ruby object.
Creating Hashes
Hashes can be created with `{}`, `Hash.new`, or with string/mixed keys using the hash-rocket `=>` syntax.
1. Symbol Key Syntax (Modern)
Use `key: value` for symbol keys — the most common Ruby style.
2. Hash Rocket Syntax (=>)
Use `key => value` for any key type — strings, integers, mixed.
3. Hash.new with Default Value
`Hash.new(default)` returns the default for any missing key instead of nil.
Accessing & Updating Values
Access values with `[]` or `fetch`. Update with `[]=`. Use `dig` for nested access.
1. [] Access
`hash[:key]` returns the value or `nil` if the key does not exist.
2. fetch — Safe Access
`fetch` raises a `KeyError` for missing keys, or returns a default.
3. dig — Nested Access
`dig` safely navigates nested hashes and arrays without raising errors.
4. Updating Values
Assign to a key with `[]=` — creates the key if it does not exist.
Adding & Deleting Keys
Add keys with `[]=` or `merge!`. Delete with `delete`, `reject!`, or `select!`.
1. delete
`delete(:key)` removes a key and returns its value.
2. slice and except
`slice` keeps only specified keys; `except` removes specified keys (Ruby 3.0+).
Traversing Hashes
Use `each`, `each_key`, `each_value`, `map`, and `any?`/`all?` to traverse and query hashes.
1. each
Iterate over every key-value pair.
2. keys, values, each_key, each_value
Extract all keys or all values as arrays.
3. map and select on Hashes
Transform or filter hash entries.
Merging Hashes
`merge` returns a new hash; `merge!` (alias `update`) merges in place. Conflicts are resolved by the second hash by default.
1. merge
`merge` combines two hashes. The second hash wins on key conflicts.
2. merge with Block (Conflict Resolution)
Pass a block to control how conflicting keys are resolved.
3. merge! (update in Place)
`merge!` modifies the receiver hash directly.
Copying Hashes
`dup` and `clone` make shallow copies. For deep copies of nested hashes, use `Marshal` or manual recursion.
1. Shallow Copy with dup
`dup` creates a new hash with the same top-level key-value pairs.
2. Deep Copy with Marshal
`Marshal.load(Marshal.dump(obj))` creates a fully independent deep copy.
Transforming Hashes
`transform_keys` and `transform_values` return new hashes with keys or values modified by a block.
1. transform_keys and transform_values
Map over just the keys or just the values of a hash.
Sorting Hashes
Hashes are not sorted by default. Use `sort_by` to return a sorted array of pairs, then convert back to a Hash with `to_h`.
1. sort_by Key or Value
`sort_by` returns an array of `[key, value]` pairs in sorted order.
Additional Hash Operations
Check key/value existence, count entries, invert, flatten to array, and group collections.
1. Existence Checks
`key?`, `value?`, `any?`, `all?`, `empty?`, `size`.
2. invert and to_a
`invert` swaps keys and values; `to_a` converts to an array of pairs.
3. group_by
`group_by` groups an array's elements into a hash by a computed key.