The Facets gem provides a rekey
method that does exactly what you're wanting.
As long as you're okay with a dependency on the Facets gem, you can pass a hash of mappings to rekey
and it will return a new hash with the new keys:
require 'facets/hash/rekey'
ages = { "Bruce" => 32, "Clark" => 28 }
mappings = {"Bruce" => "Bruce Wayne", "Clark" => "Clark Kent"}
ages.rekey(mappings)
=> {"Bruce Wayne"=>32, "Clark Kent"=>28}
If you want to modify ages hash in place, you can use the rekey!
version:
ages.rekey!(mappings)
ages
=> {"Bruce Wayne"=>32, "Clark Kent"=>28}