2014-09-23 87 views
0

爲什麼下面這段代碼會導致3的無限循環?紅寶石塊中的無限循環

a = [1,2,3,4,5,6,7,8,9,10]  
a.each {|value| puts a.insert(value,3)} 
+1

你知道'insert'是做什麼的,不是嗎? http://www.ruby-doc.org/core-2.1.3/Array.html#method-i-insert – 2014-09-23 10:01:17

+0

什麼是3的無限循環? – sawa 2014-09-23 10:10:54

+0

它只是繼續打印3一行接着另一個 – 2014-09-23 10:14:29

回答

3

的問題是,insert改變原始數組:

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

你可能就要什麼是這樣的:

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迭代指數,不價值。這可能是這裏要做的正確的事情,因爲insert將索引作爲第一個參數。
  • dup在每次迭代中重複數組,因此a保持不變。