如果键存在,如何在散列中重命名键

时间:2022-03-01 10:47:03

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.

如何优雅地将key:foo重命名为新的key:test?如果:foo的散列条目不存在,则不应该修改散列。

1 个解决方案

#1


7  

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

#1


7  

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