Search code examples
rubyhashmaphashtable

How to rename a key in a hash if it exists


I have the following hash:

a = {
  foo: 'bar',
  answer: '42'
}

How can I elegantly rename the key :foo to a new key :test? If the hash entry for :foo does not exist, the hash should not be altered.


Solution

  • a[:test] = a.delete(:foo) if a.key?(:foo)