Reputation: 20171
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?
Upvotes: 0
Views: 11802
Reputation: 1647
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 :
Upvotes: 1
Reputation: 121000
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.
Upvotes: 6
Reputation: 80065
hash = {"some_wierd_name"=>"cheesemonster"}
hash["preferred_name"] = hash["some_wierd_name"]
hash.delete("some_wierd_name")
Upvotes: 3
Reputation: 20171
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
Upvotes: 0