0
0
RubyHow-ToBeginner · 3 min read

How to Invert a Hash in Ruby: Simple Guide

In Ruby, you can invert a hash by using the invert method, which swaps keys and values. For example, {a: 1, b: 2}.invert returns {1 => :a, 2 => :b}.
📐

Syntax

The invert method is called on a hash object and returns a new hash with keys and values swapped.

Syntax:

hash.invert

Here, hash is the original hash. The method returns a new hash where each original value becomes a key, and each original key becomes a value.

ruby
hash = {a: 1, b: 2}
inverted_hash = hash.invert
💻

Example

This example shows how to invert a hash with symbol keys and integer values. The invert method swaps keys and values, creating a new hash.

ruby
original_hash = {apple: 10, banana: 20, cherry: 30}
inverted_hash = original_hash.invert
puts inverted_hash
Output
{10=>:apple, 20=>:banana, 30=>:cherry}
⚠️

Common Pitfalls

When inverting a hash, if the original hash has duplicate values, only one key will be kept in the inverted hash because keys must be unique.

For example, if two keys have the same value, the last one will overwrite the previous one in the inverted hash.

ruby
hash = {a: 1, b: 2, c: 1}
inverted = hash.invert
puts inverted
Output
{1=>:c, 2=>:b}
📊

Quick Reference

MethodDescription
invertReturns a new hash with keys and values swapped
invert!Inverts the hash in place (modifies original hash)

Key Takeaways

Use hash.invert to swap keys and values in a Ruby hash.
Inverted hash keys must be unique; duplicate values in original hash cause data loss.
The invert method returns a new hash and does not change the original.
Use invert! to invert the hash in place if needed.