I have a hash
hash = {"some_wierd_name"=>"cheesemonster", .....}
and I want this hash as
hash = {"preferred_name"=>"cheesemonster", ......}
What is the shortest way to do that?
hash["preferred_name"] = hash.delete("some_wierd_name")
Hash keys are frozen strings, they can’t be modified inplace, and the frozen state can’t be removed from an object. That said, tricks with prepend and replace won’t work resulting in:
RuntimeError: can't modify frozen String
Therefore, there is the only possibility: to remove the old value and insert the new one.
hash is needed as the last line.hash = {"some_wierd_name"=>"cheesemonster"}
hash["preferred_name"] = hash["some_wierd_name"]
hash.delete("some_wierd_name")
hash.delete("some_wierd_name") => "cheesemonster") if this is packaged in a method, hash is needed as the last line.If we are looking to replace the key/value both, can be done easily by using rails except method. You can also use the delete method but one key/value pair at a time but be using except can remove 2 or more key/value pair.
hash = {a: 1, b:2, c: 3}
hash.except!(:a)[:d] = 4
and it is similar to these two following line
hash.except!(:a)
hash[:d] = 4
hash = {:b=>2, :c=>3, :d=>4}
Changing only key of the hash, value remains same. One can also use the reject. reject and delete_if are same.
hash[:e] = hash.delete(:d)
or
temp = hash[d]
hash.delete_if{|key| key ==:d }
hash[:e] = temp
hash = {:b=>2, :c=>3, :e=>4}
Changing only value, the key remains same. This one pretty easy.
hash[:e] = 5
References :
for a single key, use delete
hash["preferred_name"] = hash.delete("some_wierd_name")
If you need to update all the keys, i suggest using inject
new_hash = hash.inject({}) do |returned_hash, (key, value)|
returned_hash[key] = value.upcase;
returned_hash
end
inject, you can also use each_with_object to get rid of the second line in the block.value.upcase? And why not use each_with_object({}) when you're not really injecting? Or use h.merge(k => v.upcase) as the block if you are injecting. And your inject version isn't renaming any keys, it is modifying the values.
{ "preferred_name" => hash.delete("some_weird_name") }.merge hash.