Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to an Array while Iterating

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 
like image 913
Dru Avatar asked Sep 02 '12 01:09

Dru


People also ask

How do you add elements to an array in a for loop?

Getting the sum using a for loop implies that you should: Create an array of numbers, in the example int values. Create a for statement, with an int variable from 0 up to the length of the array, incremented by one each time in the loop. In the for statement add each of the array's elements to an int sum.

Can we use while loop for array?

Using while to iterate over an arrayWe can even use while loops to iterate over an array. First we define an array and find out its length, len , using the length property of arrays. Then we define an index variable to iterate over the array .

How do you add a value to an array in Python?

We can add value to an array by using the append(), extend() and the insert (i,x) functions. The append() function is used when we need to add a single element at the end of the array. The resultant array is the actual array with the new value added at the end of it.


2 Answers

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 }
like image 163
ronalchn Avatar answered Nov 11 '22 21:11

ronalchn


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.

like image 28
dfb Avatar answered Nov 11 '22 22:11

dfb