0

My goal is to take each element in multidimensional array, create 12 copies that will be processed (without changing the original value), append the processed values to the array, and repeat if necessary to meet the total number of desired values:

total = 4
arr = Array.new(1) { Array.new(3, 127.5) }

while arr.count < total
  tmp = arr

  tmp.each do |item|
    new_arr = Array.new(12, item)
    #processing the 12 arrays I just created would happen here
    arr.concat new_arr
    puts arr.count 
  end 
end

This portion of the code creates an infinite loop. I can not understand why.

4 Answers 4

1

Your issue is on assigning tmp with arr. They are the same object as you can see here:

> arr = [1,2,3]
=> [1, 2, 3]
> tmp = arr
=> [1, 2, 3]
> arr.concat([4,5,6])
=> [1, 2, 3, 4, 5, 6]
> tmp
=> [1, 2, 3, 4, 5, 6]

You'd need to make a copy of the array by using dup or clone pending on your needs

if you do tmp = arr.dup it should fix your issue.

Sign up to request clarification or add additional context in comments.

Comments

1

arr and tmp are the same object. While adding to arr , tmp grows, so there are new subarrays for tmp.each to process.

Comments

0

Your infinite loop is happening because you're adding items to the array in a second loop inside it, so subsequent iterations are acting on the previously added entries. Also, you are not making a copy of arr when you do 'tmp = arr', you are setting a reference. Check this out and see if it helps:

> arr = ['test','test1','test2']
=> ["test", "test1", "test2"]
> tmp = arr
=> ["test", "test1", "test2"]
> arr << 'test3'
=> ["test", "test1", "test2", "test3"]
> tmp
=> ["test", "test1", "test2", "test3"]
> tmp = arr.dup
=> ["test", "test1", "test2", "test3"]
> arr << 'test3'
=> ["test", "test1", "test2", "test3", "test3"]
> tmp
=> ["test", "test1", "test2", "test3"]

With that in mind, maybe you could try something like:

total = 4
original_arr = Array.new(1) { Array.new(3, 127.5)}
new_arr = []
total.times do |i|
  original_arr.each do |v|
    new_arr << Array.new(12, v)
    puts i
  end
end

Comments

-1

just use

arr += new_arr

instead of

arr.concat new_arr

3 Comments

providing the answer help, but answering why is creating a infinite loop will make it much better
Then you're not answering the question
The questioned was already marked as answered and I don't have enough points to comment..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.