79410346

Date: 2025-02-04 00:50:25
Score: 0.5
Natty:
Report link

If you're on Ruby 3 or above:

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"}

Notes:

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.

Reasons:
  • Blacklisted phrase (0.5): How can I
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: Lidiane T.