Adding to an Array while Iterating

2019-06-19 00:26发布

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 

2条回答
劫难
2楼-- · 2019-06-19 00:47

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 }
查看更多
等我变得足够好
3楼-- · 2019-06-19 01:08
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.

查看更多
登录 后发表回答