Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

key

hash

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        } 
like image 665
Chanpory Avatar asked Nov 09 '10 19:11

Chanpory


People also ask

How do you rename a hash key in Ruby?

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.

How do you update a value in a hash Ruby?

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.

Can a hash have multiple values Ruby?

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.


Video Answer


2 Answers

ages = { 'Bruce' => 32, 'Clark' => 28 } mappings = { 'Bruce' => 'Bruce Wayne', 'Clark' => 'Clark Kent' }  ages.transform_keys(&mappings.method(:[])) #=> { 'Bruce Wayne' => 32, 'Clark Kent' => 28 } 
like image 50
Jörg W Mittag Avatar answered Nov 11 '22 21:11

Jörg W Mittag


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.

like image 30
barbolo Avatar answered Nov 11 '22 19:11

barbolo