我正在學習Ruby,我很沮喪。這裏有三個代碼示例這是爲了做同樣的事情:Ruby:循環與救援的區別
實例1
animals = %w(dog cat horse goat snake frog)
count = 0
begin
animals.each do |animal|
puts "The current animal is #{animal}"
break if count == 10
count += 1
raise if animal == 'horse'
end
rescue
retry
end
它工作正常。我試圖做同樣的伎倆與for
(也許我得到了結束序列中丟失):
例2
animals = %w(dog cat horse goat snake frog)
count = 0
for animal in animals
begin
puts "The current animal is #{animal}"
break if count == 10
count += 1
raise if animal == 'horse'
end
rescue
retry
end
它不工作()。我試過在for循環中使用retry(好吧,它實際上是我的第一次嘗試),但不是重試整個循環,而是重試當前的迭代,給出一隻狗,一隻貓和一羣馬:
例3
animals = %w(dog cat horse goat snake frog)
count = 0
for animal in animals
begin
puts "The current animal is #{animal}"
break if count == 10
count += 1
raise if animal == 'horse'
rescue
retry
end
end
那我做錯了嗎?在循環內重試整個錯誤的想法?爲什麼each
和for
循環在這裏以不同的方式工作?如何從for
循環中進行正確的重試?
在此基礎上螺紋:https://teamtreehouse.com/forum/getting-an-error-when-practicing-retry-command-in-forloops
對於初學者來說,嘗試縮進一致的東西 – 2015-02-23 14:27:53
將'begin'和'rescue'的'in' _inside_放在'for for'之外,因爲這是第一個示例中的示例 – 2015-02-23 14:29:19