8

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 Answers 2

11

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 }
Sign up to request clarification or add additional context in comments.

Comments

5
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.

Comments

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.