0

Why does the following piece of code result in an infinite loop of 3's?

a = [1,2,3,4,5,6,7,8,9,10]     
a.each {|value| puts a.insert(value,3)}
7
  • 1
    You know what insert does, don't you? ruby-doc.org/core-2.1.3/Array.html#method-i-insert Commented Sep 23, 2014 at 10:01
  • What is an infinite loop of 3's? Commented Sep 23, 2014 at 10:10
  • It just keeps printing 3 one line after the other Commented Sep 23, 2014 at 10:14
  • Then write it like that. Commented Sep 23, 2014 at 10:15
  • @user3078066: your code should not be printing only 3's. There should be other characters as well. Commented Sep 23, 2014 at 10:16

1 Answer 1

3

The problem is that insert changes the original array:

a = [1,2,3,4,5,6,7,8,9,10]
a.each do |value|
  a.insert(value, 3)
  p a
end

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                   # original, ^ marks current value
#  ^
# [1, 3, 2, 3, 4, 5, 6, 7, 8, 9, 10]                # inserted 3 at position 1
#     ^
# [1, 3, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10]             # inserted 3 at position 3
#        ^
# [1, 3, 3, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10]          # inserted 3 at position 2
#           ^
# [1, 3, 3, 3, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10]       # inserted 3 at position 2
#              ^
# [1, 3, 3, 3, 3, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10]    # inserted 3 at position 2
#                 ^
# [1, 3, 3, 3, 3, 3, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10] # inserted 3 at position 2
#                    ^
# ...                                               # continues forever ...

What you probably want instead is something like this:

a = [1,2,3,4,5,6,7,8,9,10]
a.each_index {|index| p a.dup.insert(index, 3) }
# [3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# [1, 3, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# [1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10]
# [1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10]
# [1, 2, 3, 4, 3, 5, 6, 7, 8, 9, 10]
# [1, 2, 3, 4, 5, 3, 6, 7, 8, 9, 10]
# [1, 2, 3, 4, 5, 6, 3, 7, 8, 9, 10]
# [1, 2, 3, 4, 5, 6, 7, 3, 8, 9, 10]
# [1, 2, 3, 4, 5, 6, 7, 8, 3, 9, 10]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 10]
  • each_index iterates over the indices, not the values. This is likely the correct thing to do here, because insert takes an index as first argument.
  • dup duplicates the array on every iteration so a remains unchanged.
Sign up to request clarification or add additional context in comments.

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.