Reason #76 •
March 17th, 2026
Inverting hashes with Hash#invert
Sometimes we model our hashes for lookups in one direction first, then later need the reverse lookup. Hash#invert gives us that in one move.
Ruby
STATUS_CODES_BY_NAME = {
ok: 200,
found: 302,
not_found: 404,
server_error: 500
}
STATUS_CODE_BY_CODE = STATUS_CODES_BY_NAME.invert
STATUS_CODES_BY_NAME[:not_found]
# => 404
STATUS_CODE_BY_CODE[404]
# => :not_found
JavaScript
const STATUS_CODES_BY_NAME = {
ok: 200,
found: 302,
not_found: 404,
server_error: 500
};
const STATUS_CODE_BY_CODE = Object.fromEntries(
Object.entries(STATUS_CODES_BY_NAME).map(([key, value]) => [value, key])
);
console.log(STATUS_CODES_BY_NAME.not_found);
// => 404
console.log(STATUS_CODE_BY_CODE[404]);
// => 'not_found'
One practical gotcha: if multiple keys share the same value, the last one wins. You likely want to avoid invert unless all values are unique 🙃
History
Hash#invert has been part of Ruby since version 1.1, released in 2001.
The method was likely inspired by the reverse method in Perl, which can be used to reverse both the order of String characters as well as the key-value pairs in hashes.