Use merge: a.merge(b) returns a new hash with the keys of both, and on a shared key the value from b wins. merge! (alias update) changes a in place. To keep the existing value instead, pass a block: a.merge(b) { |_key, old, _new| old }.
A Ruby Hash keeps its keys in insertion order, and merge is the one method for joining two of them: a block decides what happens to keys found in both. The sections below cover merge, merge! and adding a single key, keeping or combining values on a conflict, merging nested hashes, picking keys with slice and except, changing keys and values (symbols, every value, swapping keys and values), and copying a hash without sharing its nested objects, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1merge, merge! and adding a keyRecommended
a.merge(b) leaves both hashes alone and returns a new one. It takes any number of hashes, and for a key that appears more than once the last one wins. The double splat { **a, **b } builds the same hash and reads like JavaScript's { ...a, ...b }; Python's a | b does not exist for Ruby hashes. merge! and its alias update write into the receiver. To add one key, assign it with h[key] = value (or h.store(key, value), the same thing).
defaults = { color: "blue", size: "M", qty: 1 }
order = { size: "L", gift: true }
# merge returns a new hash; on a shared key the argument wins
merged = defaults.merge(order)
p merged
p defaults
# Several hashes in one call (later ones win)
p defaults.merge(order, { qty: 3 })
# The double splat builds the same hash
p({ **defaults, **order })
# merge! (alias update) changes the receiver in place
settings = { theme: "dark" }
settings.merge!(font: "mono")
settings.update(theme: "light")
p settings
# Adding one key: assign, or store
settings[:lang] = "en"
settings.store(:tabs, 2)
p settings
# Assigning to an existing key keeps its place
settings[:theme] = "solarized"
p settings.keys
Output
size becomes "L" because order is the argument, and defaults still prints size: "M" afterwards. Merged keys keep their first position, and new keys go to the end, so gift comes last. After update(theme: "light"), theme is still the first key, and reassigning it later does not move it either. The output uses the Ruby 3.4 format {color: "blue"}; older Rubies and most Stack Overflow answers show {:color=>"blue"} for the same hash. Calling merge! on a frozen hash raises FrozenError: can't modify frozen Hash: {a: 1}, while merge still works because it builds a new hash.
2Keep the existing value, or combine both
Give merge a block and Ruby calls it for every key found in both hashes, with the key, the old value and the new value; whatever the block returns goes into the result. Return old to merge without overwriting. Rails has reverse_merge for this (from ActiveSupport); in plain Ruby, swap the receiver and the argument: incoming.merge(current) keeps the values of current. The block can also add counts, join arrays or skip nil values. merge! takes the same block.
current = { color: "red", qty: 2 }
incoming = { color: "blue", size: "M", qty: nil }
# The block runs for keys in both hashes; return the old value
p current.merge(incoming) { |_key, old, _new| old }
# Same values: make the hash you want to keep the argument
# (this is Rails' current.reverse_merge(incoming))
p incoming.merge(current)
# Only fill in what is missing or nil
p current.merge(incoming) { |_key, old, new| new.nil? ? old : new }
# Combine the two values instead of choosing one
a = { apples: 3, pears: 1 }
b = { apples: 2, plums: 5 }
p a.merge(b) { |_key, x, y| x + y }
tags_a = { ruby: ["web"], go: ["cli"] }
tags_b = { ruby: ["scripts"] }
p tags_a.merge(tags_b) { |_key, x, y| x + y }
# merge! takes the same block
stock = { apples: 3 }
stock.merge!(apples: 4, kiwis: 1) { |_key, x, y| x + y }
p stock
# The block only runs for shared keys
a.merge(b) { |key, *| puts "conflict on #{key}"; 0 }
Output
The first two lines hold the same pairs, color: "red" and qty: 2, in a different order: the block version keeps current's key order, the swapped version follows incoming's. The third line takes "blue" from incoming but keeps qty: 2 because the new value was nil. Adding gives apples: 5 and joining arrays gives ["web", "scripts"]. Only apples is in both a and b, so the last line prints a single conflict on apples.
3Merge nested hashes (deep merge)
merge is shallow: when both hashes hold a hash under the same key, the inner hash from the argument replaces the other one whole. Rails adds deep_merge through ActiveSupport; plain Ruby has no such method, but a merge block that calls itself does the job in a few lines. It recurses when both values are hashes and lets the new value win otherwise.
config = { db: { host: "localhost", port: 5432 }, debug: false }
local = { db: { host: "db.internal" }, debug: true }
# merge is shallow: the inner hash is replaced, port is lost
p config.merge(local)
def deep_merge(a, b)
a.merge(b) do |_key, old, new|
old.is_a?(Hash) && new.is_a?(Hash) ? deep_merge(old, new) : new
end
end
p deep_merge(config, local)
p config
Output
The plain merge drops port: 5432, since {host: "db.internal"} replaces the whole inner hash. deep_merge keeps the port and takes the new host, and config is unchanged afterwards because every level uses merge, not merge!. Without Rails, {}.deep_merge({}) raises undefined method 'deep_merge' for an instance of Hash. To join arrays at any depth too, add a branch for two arrays that returns old + new.
4Pick or drop keys: slice, except and select
slice returns a hash with only the keys you name, and except (added in Ruby 3.0; Rails had it earlier) returns one without them. For a condition on the key or the value, select (alias filter) keeps the pairs the block accepts and reject drops them; both return a hash. filter_map returns an array, handy when you want only the keys. The bang versions and delete change the hash itself.
user = { id: 7, name: "Ann", email: "[email protected]", password: "s3cret" }
# Keep only some keys, or drop some keys
p user.slice(:id, :name)
p user.except(:password)
# Keys that are missing are ignored
p user.slice(:id, :phone)
# select / filter and reject test each pair with a block
scores = { ann: 91, bob: 62, cy: 78, dan: 45 }
p scores.select { |_name, score| score >= 70 }
p scores.reject { |_name, score| score >= 70 }
p scores.filter_map { |name, score| name if score < 50 }
# Keys that match a pattern
params = { "user_id" => 1, "user_name" => "Ann", "page" => 2 }
p params.select { |key, _| key.start_with?("user_") }
# In place: select!, reject!, delete
scores.reject! { |_name, score| score < 50 }
p scores
p scores.delete(:bob)
p scores
Output
slice(:id, :phone) gives {id: 7} with no error for the missing key. select and reject split the scores into {ann: 91, cy: 78} and {bob: 62, dan: 45}, while filter_map returns the array [:dan]. The string keys print with =>, as in {"user_id" => 1, "user_name" => "Ann"}. delete returns the removed value, 62, or nil if the key was not there.
5Change keys and values: symbols, every value, invert
transform_keys(&:to_sym) turns string keys into symbols, and transform_values runs a block on every value; both return a new hash (the ! versions change it in place). When the strings come from JSON, parse with symbolize_names: true and you get symbols at every level. to_h with a block changes keys and values together. invert swaps keys and values, and since keys must be unique, values that repeat collapse into one key.
require 'json' # String keys to symbols (and back) data = { "name" => "Ann", "age" => 31 } p data.transform_keys(&:to_sym) p data.transform_keys(&:to_sym).transform_keys(&:to_s) # transform_keys only touches the top level p({ "user" => { "id" => 1 } }.transform_keys(&:to_sym)) # Parse JSON straight to symbol keys, at every level json = '{"name": "Ann", "tags": [{"id": 1}]}' p JSON.parse(json) p JSON.parse(json, symbolize_names: true) # Change every value prices = { apple: 1.2, pear: 0.8 } p prices.transform_values { |v| (v * 1.1).round(2) } p prices.to_h { |k, v| [k.to_s.upcase, v] } # Rename some keys with a mapping hash p data.transform_keys({ "name" => "full_name" }) # Swap keys and values codes = { us: "USA", fr: "FRA" } p codes.invert # Duplicate values collapse: the last key wins sizes = { s: "small", m: "medium", tiny: "small" } p sizes.invert # Keep every key with group_by p sizes.group_by { |_k, v| v }.transform_values { |pairs| pairs.map(&:first) }
Output
The nested line shows the limit of transform_keys: {user: {"id" => 1}} still has a string key inside. Rails' deep_symbolize_keys handles that; in plain Ruby, a JSON round trip, JSON.parse(h.to_json, symbolize_names: true), gives {user: {id: 1}}. Passing a hash to transform_keys renames just the keys it lists (Ruby 3.0 and later). In the invert of sizes, :s is gone: "small" maps to :tiny, the last key that had it. The group_by line keeps both as "small" => [:s, :tiny].
6Copy a hash before changing it
b = a copies nothing: both names point to the same hash. dup and clone make a new hash, but a shallow one: the values are the same objects, so an array or hash inside is still shared. clone also copies the frozen state. For a deep copy of plain data, dump the hash with Marshal and load it back.
original = { name: "Ann", tags: ["admin"], address: { city: "Oslo" } }
copy = original.dup
copy[:name] = "Bob"
copy[:tags] << "dev"
copy[:address][:city] = "Rome"
# The top-level change stayed in the copy...
p copy[:name]
p original[:name]
# ...but the nested array and hash are shared
p original[:tags]
p original[:address]
p copy[:tags].equal?(original[:tags])
# Deep copy: serialize and load back
source = { name: "Ann", tags: ["admin"], address: { city: "Oslo" } }
deep = Marshal.load(Marshal.dump(source))
deep[:tags] << "dev"
deep[:address][:city] = "Rome"
p source
p deep
# clone also copies the frozen state; dup does not
frozen = { a: 1 }.freeze
p frozen.clone.frozen?
p frozen.dup.frozen?
# Plain assignment copies nothing
alias_ref = source
alias_ref[:name] = "Cy"
p source[:name]
Output
Renaming in the copy left original[:name] as "Ann", but the dup gave original the new tag and the new city: ["admin", "dev"] and {city: "Rome"}, and equal? confirms the two hashes hold the very same array. The Marshal copy is independent, so source still prints ["admin"] and Oslo. Marshal cannot copy everything: a hash with a default block raises TypeError: can't dump hash with default proc, and procs or IO objects fail the same way. Merging also builds a new hash, but just as shallowly as dup.
7Which should you use?
| Method | Result | Best for |
|---|---|---|
| a.merge(b) | New hash, b wins | Most merges |
| a.merge!(b) / a.update(b) | Changes a | Adding many keys to a hash you own |
| { **a, **b } | New hash, b wins | Building a hash with extra literal keys |
| a.merge(b) { |k, old, new| old } | New hash, a wins | Merge without overwriting, or combine values |
| b.merge(a) | New hash, a wins | Rails reverse_merge without Rails |
| deep_merge(a, b) | Your own method | Nested hashes such as config |
| h[k] = v | Changes h | Adding or updating one key |
| h.slice / h.except | New hash | Keeping or dropping named keys |
| Marshal.load(Marshal.dump(h)) | Deep copy | Changing nested data without touching the original |
Frequently asked questions
What is the Ruby version of Python's a | b or JavaScript's { ...a, ...b }?
a.merge(b), or { **a, **b }, which also works with string keys. Ruby hashes have no | operator: { a: 1 } | { b: 2 } raises NoMethodError: undefined method '|' for an instance of Hash. Python's a |= b and JavaScript's Object.assign(a, b) are a.merge!(b) in Ruby.
What is the difference between merge, merge! and update?
merge returns a new hash and leaves the receiver alone. merge! and update are the same method: they write the other hash's pairs into the receiver and return it. Use merge unless you mean to change the hash; on a frozen hash merge! raises FrozenError.
Does Ruby have reverse_merge and deep_merge?
Not plain Ruby: both come from Rails (ActiveSupport), along with deep_symbolize_keys and with_indifferent_access. Instead of h.reverse_merge(defaults), write defaults.merge(h). For deep_merge, use a merge block that calls itself when both values are hashes, as in section 3.
Does merge keep the order of the keys?
Yes. Ruby hashes keep insertion order, so the result lists the receiver's keys first, in their order, then the new keys from the argument. A key that exists in both stays in its original position even though its value changes.
How do I add a new key to a hash?
Assign it: h[:key] = value. h.store(:key, value) is the same method under another name. To add several keys at once, use h.merge!(a: 1, b: 2), or h.merge(a: 1, b: 2) to get a new hash. Ruby has no push or add for hashes.
Why does my output look different from older Stack Overflow answers?
Ruby 3.4 changed how hashes print. A hash that older Rubies showed as {:name=>"Ann", "age"=>31} now prints as {name: "Ann", "age" => 31}. The hash is the same; only inspect changed, so code that compares the printed text needs updating.