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
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.
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 .
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.
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With