Adding to an array during iteration

Why does this code “block” a ruby? And what is the best way to overcome this? I posted the solution below. Is there any other way to do this? Thanks in advance!

the code:

nums = [1, 2, 3] nums.each { |i| nums << i + 1 } 

My decision:

 nums = [1, 2, 3] adjustments = [] nums.each { |i| adjustments << i + 1 } nums += adjustments 
+6
source share
2 answers

This is because everyone uses an enumerator (so it never reaches the end if you keep adding to it).

You can duplicate an array before applying each of them.

 nums = [1, 2, 3] nums.dup.each { |i| nums << i + 1 } 

Another way is to add additional elements defined by the map:

 nums = [1, 2, 3] nums += nums.map { |i| i + 1 } 
+8
source
 nums = [1, 2, 3] nums.each { |i| nums << i + 1 } 

You add to the array as you iterate over it, so it never finishes executing.

+4
source

Source: https://habr.com/ru/post/924372/


All Articles