Hash.fetch / store / delete / merge
Methods for getting, setting, deleting, and merging hash values. These are commonly used in practice — fetch for safe value retrieval, and merge for combining multiple hashes.
Syntax
# Returns the value for a key (raises an error or returns a default if the key is missing).
hash.fetch(key)
hash.fetch(key, default)
hash.fetch(key) { |k| compute default }
# Sets a key-value pair.
hash.store(key, value)
hash[key] = value
# Removes a key and its associated value.
hash.delete(key)
hash.delete(key) { |k| value to return if not found }
# Returns a new hash that merges two hashes together.
hash.merge(other_hash)
hash.merge(other_hash) { |key, old, new| handle conflict }
hash.merge!(other_hash) # destructive
Method List
| Method | Description |
|---|---|
| fetch(key) | Returns the value for the given key. Raises a KeyError if the key does not exist. |
| fetch(key, default) | Returns the default value if the key does not exist. |
| store(key, value) | Sets a key-value pair. Equivalent to []=. |
| delete(key) | Removes the specified key and its value, and returns the deleted value. Returns nil if the key does not exist. |
| delete_if { |k, v| ... } | Removes all pairs for which the block returns true (destructive). |
| merge(other) | Returns a new hash that combines two hashes. If keys overlap, the value from the argument takes precedence. |
| merge!(other) | Merges another hash into the original hash (destructive). update is an alias. |
| slice(k1, k2, ...) | Returns a new hash containing only the specified keys. |
Sample Code
config = { host: 'localhost', port: 3000 }
# fetch: safely access potentially missing keys
puts config.fetch(:host) # "localhost"
puts config.fetch(:timeout, 30) # 30 (default value)
puts config.fetch(:name) { |k| "#{k} is not configured" }
# => "name is not configured"
# store / []= to set values
config.store(:ssl, false)
config[:debug] = true
puts config.inspect
# {:host=>"localhost", :port=>3000, :ssl=>false, :debug=>true}
# delete to remove a key
deleted = config.delete(:debug)
puts deleted # true (the deleted value)
puts config.inspect # {:host=>"localhost", :port=>3000, :ssl=>false}
# merge: combine hashes
defaults = { timeout: 60, retry: 3, debug: false }
custom = { debug: true, host: 'example.com' }
merged = defaults.merge(custom)
puts merged.inspect
# {:timeout=>60, :retry=>3, :debug=>true, :host=>"example.com"}
# merge with a block to handle key conflicts
h1 = { a: 1, b: 2 }
h2 = { b: 3, c: 4 }
result = h1.merge(h2) { |key, old, new_val| old + new_val }
puts result.inspect # {:a=>1, :b=>5, :c=>4} (b is 2+3=5, not 1+2+3)
# slice: extract only the keys you need
user = { id: 1, name: 'Taro', password: 'secret', email: 'taro@example.com' }
public_info = user.slice(:id, :name, :email)
puts public_info.inspect # {:id=>1, :name=>"Taro", :email=>"taro@example.com"}
Notes
Accessing a key with [] silently returns nil if the key does not exist. To prevent unexpected nil values from creeping in, use fetch when a key is required. Since fetch raises a KeyError when a key is missing, it helps you catch bugs early.
merge is a non-destructive method that returns a new hash. If you want to modify the original hash in place, use merge! (or its alias update). You can pass a block to fine-tune how conflicting keys are resolved.
slice, added in Ruby 2.5, is useful for extracting only the keys you need from a hash — for example, to strip unwanted fields from an API response. To exclude specific keys instead, use reject.
If you find any errors or copyright issues, please contact us.