How to elegantly rename all keys in a hash in Ruby? [duplicate] How to elegantly rename all keys in a hash in Ruby? [duplicate] ruby ruby

How to elegantly rename all keys in a hash in Ruby? [duplicate]


ages = { 'Bruce' => 32, 'Clark' => 28 }mappings = { 'Bruce' => 'Bruce Wayne', 'Clark' => 'Clark Kent' }ages.transform_keys(&mappings.method(:[]))#=> { 'Bruce Wayne' => 32, 'Clark Kent' => 28 }


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.


There's the under-utilized each_with_object method in Ruby as well:

ages = { "Bruce" => 32, "Clark" => 28 }mappings = { "Bruce" => "Bruce Wayne", "Clark" => "Clark Kent" }ages.each_with_object({}) { |(k, v), memo| memo[mappings[k]] = v }