Method: Hash#transform_keys!
- Defined in:
- hash.c
#transform_keys! {|key| ... } ⇒ Hash #transform_keys! ⇒ Object
Invokes the given block once for each key in hsh, replacing it with the new key returned by the block, and then returns hsh. This method does not change the values.
h = { a: 1, b: 2, c: 3 }
h.transform_keys! {|k| k.to_s } #=> { "a" => 1, "b" => 2, "c" => 3 }
h.transform_keys!(&:to_sym) #=> { a: 1, b: 2, c: 3 }
h.transform_keys!.with_index {|k, i| "#{k}.#{i}" }
#=> { "a.0" => 1, "b.1" => 2, "c.2" => 3 }
If no block is given, an enumerator is returned instead.
3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 |
# File 'hash.c', line 3084 static VALUE rb_hash_transform_keys_bang(VALUE hash) { RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size); rb_hash_modify_check(hash); if (!RHASH_TABLE_EMPTY_P(hash)) { long i; VALUE pairs = rb_hash_flatten(0, NULL, hash); rb_hash_clear(hash); for (i = 0; i < RARRAY_LEN(pairs); i += 2) { VALUE key = RARRAY_AREF(pairs, i), new_key = rb_yield(key), val = RARRAY_AREF(pairs, i+1); rb_hash_aset(hash, new_key, val); } } return hash; } |