How to elegantly rename all keys in a hash in Ruby?

Chanpory picture Chanpory · Nov 9, 2010 · Viewed 55.9k times · Source

I have a Ruby hash:

ages = { "Bruce" => 32,
         "Clark" => 28
       }

Assuming I have another hash of replacement names, is there an elegant way to rename all the keys so that I end up with:

ages = { "Bruce Wayne" => 32,
         "Clark Kent" => 28
       }

Answer

Jörg W Mittag picture Jörg W Mittag · Nov 9, 2010
ages = { 'Bruce' => 32, 'Clark' => 28 }
mappings = { 'Bruce' => 'Bruce Wayne', 'Clark' => 'Clark Kent' }

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