End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Hash#transform_keys!
hash.transform_keys! {|key| ... } → self
hash.transform_keys!(hash2) → self
hash.transform_keys!(hash2) {|other_key| ...} → self
hash.transform_keys! → new_enumerator
hash.c
View on GitHub ↗
static VALUE
rb_hash_transform_keys_bang(int argc, VALUE *argv, VALUE hash)
{
VALUE trans = 0;
int block_given = 0;
argc = rb_check_arity(argc, 0, 1);
if (argc > 0) {
trans = to_hash(argv[0]);
block_given = rb_block_given_p();
}
else {
RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
}
rb_hash_modify_check(hash);
if (!RHASH_TABLE_EMPTY_P(hash)) {
long i;
VALUE new_keys = hash_alloc(0);
VALUE pairs = rb_ary_tmp_new(RHASH_SIZE(hash) * 2);
rb_hash_foreach(hash, flatten_i, pairs);
for (i = 0; i < RARRAY_LEN(pairs); i += 2) {
VALUE key = RARRAY_AREF(pairs, i), new_key, val;
if (!trans) {
new_key = rb_yield(key);
}
else if ((new_key = rb_hash_lookup2(trans, key, Qundef)) != Qundef) {
/* use the transformed key */
}
else if (block_given) {
new_key = rb_yield(key);
}
else {
new_key = key;
}
val = RARRAY_AREF(pairs, i+1);
if (!hash_stlike_lookup(new_keys, key, NULL)) {
rb_hash_stlike_delete(hash, &key, NULL);
}
rb_hash_aset(hash, new_key, val);
rb_hash_aset(new_keys, new_key, Qnil);
}
rb_ary_clear(pairs);
rb_hash_clear(new_keys);
}
return hash;
}
Same as Hash#transform_keys but modifies the receiver in place instead of returning a new hash.
Ruby version changes
-
3.0
-
Hash#transform_keysandHash#transform_keys!now accept a hash that maps keys to new keys. [Feature #16274]
-
See also
#transform_keys
#transform_values
#to_s
#transform_values!
also in
4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0