Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Hash#transform_keys
hash.transform_keys {|key| ... } → new_hash
hash.transform_keys(hash2) → new_hash
hash.transform_keys(hash2) {|other_key| ...} → new_hash
hash.transform_keys → new_enumerator
hash.c
View on GitHub ↗
static VALUE
rb_hash_transform_keys(int argc, VALUE *argv, VALUE hash)
{
VALUE result;
struct transform_keys_args transarg = {0};
argc = rb_check_arity(argc, 0, 1);
if (argc > 0) {
transarg.trans = to_hash(argv[0]);
transarg.block_given = rb_block_given_p();
}
else {
RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
}
result = rb_hash_new();
if (!RHASH_EMPTY_P(hash)) {
if (transarg.trans) {
transarg.result = result;
rb_hash_foreach(hash, transform_keys_hash_i, (VALUE)&transarg);
}
else {
rb_hash_foreach(hash, transform_keys_i, result);
}
}
return result;
}
Returns a new Hash object; each entry has:
-
A key provided by the block.
-
The value from
self.
An optional hash argument can be provided to map keys to new keys. Any key not given will be mapped using the provided block, or remain the same if no block is given.
Transform keys:
Example
h = {foo: 0, bar: 1, baz: 2} h1 = h.transform_keys {|key| key.to_s } h1 # => {"foo"=>0, "bar"=>1, "baz"=>2} h.transform_keys(foo: :bar, bar: :foo) #=> {bar: 0, foo: 1, baz: 2} h.transform_keys(foo: :hello, &:to_s) #=> {:hello=>0, "bar"=>1, "baz"=>2}
Overwrites values for duplicate keys:
Example
h = {foo: 0, bar: 1, baz: 2} h1 = h.transform_keys {|key| :bat } h1 # => {:bat=>2}
Returns a new Enumerator if no block given:
Example
h = {foo: 0, bar: 1, baz: 2} e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys> h1 = e.each { |key| key.to_s } h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
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!
#to_s
#to_proc
#transform_values
also in
4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0