instance method
Hash#invert
() -> ::Hash[V, K]
invert → new_hash
hash.c
View on GitHub ↗
static VALUE
rb_hash_invert(VALUE hash)
{
VALUE h = rb_hash_new_with_size(RHASH_SIZE(hash));
rb_hash_foreach(hash, rb_hash_invert_i, h);
return h;
}
Returns a new hash with 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}
Related: see Methods for Transforming Keys and Values.