Hash#invert
Returns:
Hash · Updated March 22, 2026 · Hash Methods ruby hash
Synopsis
hash.invert -> new_hash
Returns a new hash where each key-value pair is swapped: values become keys, and keys become values.
Description
The invert method creates a new hash by exchanging keys and values in the original hash. The original hash remains unchanged.
scores = { alice: 100, bob: 95, carol: 98 }
inverted = scores.invert
# => { 100 => :alice, 95 => :bob, 98 => :carol }
Behavior with Duplicate Values
If multiple keys map to the same value, invert causes data loss. When duplicate values exist, the last key in iteration order wins and overwrites previous entries.
inventory = { apples: 5, oranges: 5, bananas: 3 }
inverted = inventory.invert
# => { 5 => :oranges, 3 => :bananas } # :apples dropped — both had value 5
This happens because the last key processed overwrites earlier ones with the same value.
Handling Duplicate Values
To invert a hash while preserving all entries when values are not unique, use each_with_object:
inventory = { apples: 5, oranges: 5, bananas: 3 }
inverted = inventory.each_with_object({}) { |(k, v), h| (h[v] ||= []) << k }
# => { 5 => [:apples, :oranges], 3 => [:bananas] }
This approach groups keys by their shared value into arrays.
Return Value
Always returns a new Hash instance. The original hash is not modified.
original = { x: 1, y: 2 }
result = original.invert
original.object_id == result.object_id # => false
original # => { x: 1, y: 2 }
result # => { 1 => :x, 2 => :y }
See Also
- Hash#keys — returns an array of all keys in the hash
- Hash#values — returns an array of all values in the hash
- Hash#merge — merges two hashes together