This can be achieved with Hash#transform_keys
.
Using the hash from the question:
a = {
foo: 'bar',
answer: '42'
}
How can I elegantly rename the key
:foo
to a new key:test
?
=> {foo: "bar", answer: "42"}
> b = a.transform_keys(foo: :test, answer: :another_test)
=> {test: "bar", another_test: "42"}
If the hash entry for
:foo
does not exist, the hash should not be altered.
> b.transform_keys(foo: :something)
=> {test: "bar", another_test: "42"}
Hash#transform_keys
method was initially implemented in Ruby 2.5. By then, it was required to pass a block to it, which forced us to follow stricter rules when manipulating it. In Ruby 3, the method was updated to accept a hash. The purpose of this change was to provide a level of flexibility similar to the one requested in this question (such as dismissing it in case the key does not exist). More details can be found here: Feature #16274 - Transform hash keys by a hash.