Kevin McKelvin

Renaming Items in a Ruby Hash

19 June 2014

This is a pretty neat snippet of Ruby that I found to rename a key in a Ruby hash.

hash[:new_key] = hash.delete(:old_key)

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.

This StackOverflow answer contains the snippet.

Kevin McKelvin

These are the online musings of Kevin McKelvin. He is the CTO at Resource Guru, and lives in Newcastle upon Tyne, UK.