Adding to an Array while Iterating

2019-06-19 00:45发布

问题:

Why does this code 'lock up' ruby? And what is the best way to get past it? I posted my solution below. Is there another way to do this? Thanks in advance!

Code:

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

My solution:

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

回答1:

That's because each uses an enumerator (so it never reaches the end if you keep adding to it).

You can duplicate the array before applying each.

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

Another way is to append the extra elements given by map:

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


回答2:

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

You are adding to the array as you're iterating over it, so it never finishes executing.