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

后端 未结 7 1420
广开言路
广开言路 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:05

    The exact solution would depend on the format that you have the new keys in (or if you can derive the new key from the old key.)

    Assuming you have a hash h whose keys you want to modify and a hash new_keys that maps the current keys to the new keys you could do:

    h.keys.each do |key|
      h[new_keys[key]] = h[key] # add entry for new key
      k.delete(key)             # remove old key
    end
    
    0 讨论(0)
提交回复
热议问题