Is There a Solution to Bypass 'Can't Add a New Key into Hash During Iteration (Runtimeerror)'

Getting can't add a new key into hash during iteration

What is an easier way to do this?

Never ever modify a collection you're iterating. (unless you know precisely why you must do it). Instead, clone/dup the collection. You now have two copies of the same thing. Iterate one, but modify the other.

When you're done, replace the original with the modified copy (optional, subject to requirements).

In this case, it's not necessary to clone the hash before iterating and then delete keys from it. You can just build a new hash, with all keys already "adjusted" (whatever that means).

new_header_info_hash = header_info_hash.each_with_object({}) do |(k, v), result|
if boundary < k
result[k-1] = v
else
result[k] = v
end
end

Error - can't add new key into hash during iteration

Looks like there's a bug in the library. You can fix it by applying this patch:

https://github.com/chrsgrrtt/contentapi-ruby/commit/46326bce44177d1b8287a4a7167c895531eac25a

How to replace a hash key with another key

hash[:new_key] = hash.delete :old_key

How to avoid RuntimeError: dictionary changed size during iteration error?

In Python 3.x and 2.x you can use use list to force a copy of the keys to be made:

for i in list(d):

In Python 2.x calling keys made a copy of the keys that you could iterate over while modifying the dict:

for i in d.keys():

But note that in Python 3.x this second method doesn't help with your error because keys returns an a view object instead of copying the keys into a list.



Related Topics



Leave a reply



Submit