Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 重试在控制流中不工作_Ruby - Fatal编程技术网

Ruby 重试在控制流中不工作

Ruby 重试在控制流中不工作,ruby,Ruby,我正在尝试执行以下代码: animals = %w(dog cat horse goat snake frog) count = 0 for animal in animals puts "The current animal is #{animal}" break if count == 10 count += 1 retry if animal == 'horse' end 当我尝试在IRB上执行文件时,我得到以下输出: 2.0.0-p247 :001 &

我正在尝试执行以下代码:

animals = %w(dog cat horse goat snake frog)
count = 0

for animal in animals
    puts "The current animal is #{animal}"
    break if count == 10
    count += 1
    retry if animal == 'horse'
end
当我尝试在IRB上执行文件时,我得到以下输出:

2.0.0-p247 :001 > load 'loopexit.rb'
SyntaxError: loopexit.rb:19: Invalid retry
    from loopexit.rb
2.0.0-p247 :002 >

有人能告诉我这里可能有什么问题吗?

请使用
next
而不是
retry
,因为您想跳过当前迭代<代码>重试用于异常,而不是循环

但是,您的逻辑中也有一个错误:一旦知道动物是
,您就想跳过迭代,因此您应该移动循环顶部的
下一个
语句:

for animal in animals
    next if animal == 'horse'
    puts "The current animal is #{animal}"
    break if count == 10
    count += 1
end

rescue
子句中,使Ruby返回到封闭代码的顶部(
begin
关键字,或方法或块的顶部),然后再次尝试执行代码

但是你需要使用。它无条件地将迭代器或
期间直到
块碰撞到下一次迭代,而不执行块中可能剩余的任何内容

重试
不能在循环内使用

您可以按如下方式编写代码:

for animal in animals
    next if animal == 'horse'
    puts "The current animal is #{animal}"
    break if count == 10
    count += 1
end

这并不能保证完全满足您的要求,但它的编写方式更像Ruby(对我来说,更合理):

我们通常不对循环使用
。这样做会暴露中间变量,
animal
,在这种情况下,它会不必要地污染变量空间。相反,使用
each
,变量
animal
仅限于
do
块,因此变量空间不会被不必要地浪费

将计数器作为参数传递到块中,这样就可以很容易地知道看到了多少个,或者当前的索引值是什么


当然,
break if i==10
将永远不会执行,除非
animals
有超过10个元素。

因为Ruby 1.9
retry
不能再在循环中使用了

它通常跳到第一次迭代的开始。有时,您仍然可以找到参考Ruby1.8的书籍和教程,但现在不再支持

循环中的有效关键字是

  • next
    跳到下一次迭代的开始
  • redo
    跳到当前迭代的开始
  • 中断
    循环的结束

你也可以使用
(动物[0..10]-['horse'])。每种动物都有|动物|。。。结束
,这取决于你试图做什么。这不必要地污染了变量空间-你能解释一下,你这是什么意思吗?@ArupRakshit在OP的例子中,
animal
仍然会在for循环之外定义。@ArupRakshit我想他说的是在for循环之外暴露
animal
就像“污染全局名称空间”,除了在当前的方法/块范围内。
animal
可能不需要在循环之外提供。在我看来,这不是什么大问题,当然也不是我不鼓励使用for循环的主要原因,但这是一个值得注意的区别。
animals = %w(dog cat horse goat snake frog)

animals.each_with_index do |animal, i|
  next if animal == 'horse'
  puts "The current animal is #{ animal }"
  break if i == 10
end