Is there a solution to bypass 'can't add a new key into hash during iteration (RuntimeError)'?

北城余情 提交于 2019-11-30 17:36:51

Ruby since 1.9 is using lazy iteration, thus they forbid to add new keys to the hash you iterating over. As a solution you can easily duplicate hash or convert it to array before doing each.

irb(main):001:0> a={1=>1}; a.each {|k,v| a[2] = 2}
RuntimeError: can't add a new key into hash during iteration

irb(main):002:0> a={1=>1}; a.clone.each {|k,v| a[2] = 2}; a
=> {1=>1, 2=>2}

irb(main):003:0> a={1=>1}; a.to_a.each {|k,v| a[2] = 2}; a
=> {1=>1, 2=>2}

You're modifying the hash you're iterating over. You can't do it.

Instead try another approach:

keys = [1,2,3,4]
file_hash = YAML.load_file("testm.yaml")
keys.each{ |key| file_hash[key] = 'key1' }
# => {1 => 'key1', 2 => 'key1', 3 => 'key1', 4 => 'key1'}

I had the same error at

<%= stylesheet_link_tag 'application', 'data-turbolinks-track' => 'reload', media: 'all' %>

So I rewrite my code with:

<% begin %>
  <%= stylesheet_link_tag 'application', 'data-turbolinks-track' => 'reload', media: 'all' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload' %>
<% rescue %>
  <script>
    window.location.replace "#{user_session_url()}"
  </script>
<% end %>

I do not know what is causing this issue, but this workaround works for me. I tested it with

ab -n 100 -c 10 -w http://localhost:3000/es

And I did not got any error messages

Игорь Хлебников

previous answer didn't help me, so i propouse that help for me

a={1=>1}; a = a.clone; a[2] = 2; a
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!