i am finding a method to change a key's name of json object that is a hash on ruby like below
source
{ "a" => "b", "b" => "bb" }
result
{ "c" => "b", "b" => "bb" }
got a nice idea ?
i am finding a method to change a key's name of json object that is a hash on ruby like below
source
{ "a" => "b", "b" => "bb" }
result
{ "c" => "b", "b" => "bb" }
got a nice idea ?
If you need this functionality frequently, you can extend the Ruby Hash class.
Implementation would vary from ruby version to version, but roughly something like this:
class Hash
module ClassMethods
def self.replace_key(old_key, new_key)
self[new_key] = self[old_key]
self.delete(old_key)
end
end
end
Basically, creating a new key,value pair in the Hash using the new key and old value. Then deleting the original pair.
Note: Operations like this on large hashes are inadvisable from a performance perspective.