How to elegantly rename all keys in a hash in Ruby? [duplicate]
I liked Jörg W Mittag's answer, but if you want to rename the keys of your current Hash and not to create a new Hash with the renamed keys, the following snippet does exactly that:
ages = { "Bruce" => 32, "Clark" => 28 }mappings = {"Bruce" => "Bruce Wayne", "Clark" => "Clark Kent"}ages.keys.each { |k| ages[ mappings[k] ] = ages.delete(k) if mappings[k] }ages
There's also the advantage of only renaming the necessary keys.
Performance considerations:
Based on the Tin Man's answer, my answer is about 20% faster than Jörg W Mittag's answer for a Hash with only two keys. It may get even higher performance for Hashes with many keys, specially if there are just a few keys to be renamed.