Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a key in a hash if it exists

I have the following hash:

a = {
  foo: 'bar',
  answer: '42'
}

How can I elegantly rename the key :foo to a new key :test? If the hash entry for :foo does not exist, the hash should not be altered.

like image 901
Razer Avatar asked Aug 13 '14 09:08

Razer


People also ask

How do you check if a key exists in a hash?

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

How do I change the key on a map?

To change a HashMap key, you look up the value object with get, then remove the old key and put it with the new key. To change the fields in a value object, look the value object up by key with get, then use its setter methods. To replace the value object in its entirely, just put a new value object at the old key.

How do I change the hash key in Ruby?

The contents of a certain hash can be replaced in Ruby by using the replace() method. It replaces the entire contents of a hash with the contents of another hash.


1 Answers

a[:test] = a.delete(:foo) if a.key?(:foo)
like image 128
sawa Avatar answered Oct 13 '22 13:10

sawa