tags:

views:

33

answers:

2

Hi

How to change all the keys of a hash by a new set of given keys ? Is there a way to do that elegantly ?

Thx JCLL

+2  A: 

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
mikej
+2  A: 

Assuming you have a Hash which maps old keys to new keys, you could do something like

Hash[hsh.map {|k, v| [key_map[k], v] }]
Jörg W Mittag