Ruby:循环和救援的不同

时间:2015-02-23 14:25:42

标签: ruby loops

我正在研究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

它不起作用(syntax error, unexpected keyword_rescue, expecting keyword_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 个答案:

答案 0 :(得分:0)

你的不一致缩进很难发现缺失(或错位的结尾),但foreach循环之间的关键区别在于开始/救援与{{1}相关的位置}或for

each使ruby返回到封闭的开始/救援(或方法)的顶部并从那里开始执行。如果该开始位于retry内,那么它将会去那里,如果forbegin之外,则整个for循环将再次执行。

答案 1 :(得分: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

但是这是一个连续的循环,因为你做了一次重试,不断让马回来,所以提出错误等,你可以使用下一个,但如果你只是想显示没有马的所有动物,以下是更多& #39; ruby​​esque&#39 ;.首先,你选择所有非马匹'动物,然后你把结果限制在前10个。

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

您可以使用isn&#t; t 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