Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Hash#invert

hash.invert → new_hash

Returns a new Hash object with the each key-value pair inverted:

Example
h = {foo: 0, bar: 1, baz: 2}
h1 = h.invert
h1 # => {0=>:foo, 1=>:bar, 2=>:baz}

Overwrites any repeated new keys: (see Entry Order):

Example
h = {foo: 0, bar: 0, baz: 0}
h.invert # => {0=>:baz}
See also #inspect #keep_if #initialize_copy #key also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1