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
Sidekiq Worker Not Getting Triggered
How Can One Set Property Values When Initializing an Object in Ruby
Write Array of Radix-2 Numeric Strings to Binary File in Ruby
Ruby: How to Check If a String Contains Multiple Items
Ftps (Tls/Ssl) from Ruby on Rails App
Split Seeds.Rb into Multiple Sections
How to Use Regex for Utf8 in Ruby
Ssl_Connect Syscall Returned=5 Errno=0 State=Sslv2/V3 Read Server Hello A
Ruby: Yield Block from a Block
Create a Human-Readable List with "And" Inserted Before the Last Element from a Ruby List
Ruby Selenium Webdriver Unable to Find Mozilla Geckodriver
How to Add "Somewhere" a 'Before(:Each)' Hook So That All Spec File Can Run It
How to Cleanly Verify If the User Input Is an Integer in Ruby
How to Loop Through Months in Ruby on Rails
Multiple Submit Buttons/Forms in Rails
Heroku: How to Push to Specific App If You Have Multiple Apps in Heroku