2015-02-23 49 views
1

我正在學習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 

那我做錯了嗎?在循環內重試整個錯誤的想法?爲什麼eachfor循環在這裏以不同的方式工作?如何從for循環中進行正確的重試?

在此基礎上螺紋:https://teamtreehouse.com/forum/getting-an-error-when-practicing-retry-command-in-forloops

+2

對於初學者來說,嘗試縮進一致的東西 – 2015-02-23 14:27:53

+0

將'begin'和'rescue'的'in' _inside_放在'for for'之外,因爲這是第一個示例中的示例 – 2015-02-23 14:29:19

回答

0

更好的方式使用計數器的第一個例子是

begin 
    animals.each_with_index do |animal, count| 
    puts "The current animal is #{animal}" 
    break if count == 10 
    count += 1 
    raise if animal == 'horse' 
    end 
rescue 
    retry # should be next 
end 

但是這是一個連續的循環,因爲你做了重試其狀態越來越馬背部等引發錯誤等,你可以而不是使用下一個,但如果你只是想顯示所有沒有這匹馬的動物,那麼下面就更像是「rubyesque」。首先,你選擇所有非「馬」的動物,那麼你限制結果到第10位。

animals 
    .reject{|animal| animal == 'horse'} 
    .take(10) 
    .each{|animal| puts "The current animal is #{animal}"} 

您例如與不rubiesque在所有,但這裏的調整代碼(縮進!)

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 # or next ? 
    end 
end 
+1

哇,您的'rubyesque'示例真的優雅。我希望有一天我能夠這樣做。 – wintermute 2015-02-23 16:16:22

0

你的不一致缺口使得它很難發現缺失(或放錯地方的結束),但你的foreach環之間的關鍵區別是在開始/救援坐落在相對於foreach

retry導致ruby返回到封閉開始/救援(或方法)的頂部並從那裏開始執行。如果該開始位於for之內,那麼它將到達那裏,如果beginfor之外,那麼整個for循環將再次執行。