How to change all the keys of a hash by a new set of given keys

后端 未结 7 1441
广开言路
广开言路 2020-12-04 19:04

How do I change all the keys of a hash by a new set of given keys?

Is there a way to do that elegantly?

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 20:02

    If you also worry about performance, this is faster:

    hsh.keys.each { |k| hsh[ key_map[k] ] = hsh.delete(k) if key_map[k] }
    

    You don't create a new Hash and you rename only the necessary keys. That gives you better performance.

    You can find more details in "How to elegantly rename all keys in a hash in Ruby?"

提交回复
热议问题