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
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.
Another way is to append the extra elements given by map:
You are adding to the array as you're iterating over it, so it never finishes executing.