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 }
This is a pretty neat snippet of Ruby that I found to rename a key in a Ruby hash. The #delete method on a hash will return the value of the key provided while removing the item from the hash. The resulting hash gets a new key assigned to the old key's value.
Modifying hashes in Ruby: Hash can be modified by adding or deleting a key value/pair in an already existing hash. Also, you can change the existing value of key in the hash.
Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With