How to elegantly rename all keys in a hash in Ruby?
hash, key, ruby
Solution
ages = { 'Bruce' => 32, 'Clark' => 28 }
mappings = { 'Bruce' => 'Bruce Wayne', 'Clark' => 'Clark Kent' }
ages.transform_keys(&mappings.method(:[]))
#=> { 'Bruce Wayne' => 32, 'Clark Kent' => 28 }
Problem
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 } ```