在Kernel#loop documentation中,有一个使用break来跳出循环的例子。否则,文档将讨论如何引发StopIteration错误。
我两个都试过了:
i=0
loop do
puts i
i+=1
break if i==10
end
i=0
loop do
puts i
i+=1
raise StopIteration if i==10
end输出是相同的。这两种方法之间有区别吗?我认为应该有,否则为什么要费心定义一个error类和随之而来的所有管理呢?
发布于 2015-01-05 02:14:30
break是ruby中的一个关键字,它终止了最内部的循环,无论是loop、for还是更多(请参阅here)。
StopIteration是一个异常,它被Kernel.loop捕获(参见here)。
因此,在您的场景中,它们是相同的,但在不同的场景中,它们的行为会有所不同:
puts "first run"
for i in 0..20 do
puts i
break if i==10
end
puts "first done"
puts "second run"
for i in 0..20 do
puts i
raise StopIteration if i==10
end
puts "second done" # <= will not be printed下面是一个场景,当break不能使用时,可以使用StopIteration:
puts "first run"
def first_run(i) # will not compile
puts i
break if i==10
end
i=0
loop do
first_run(i)
i+=1
end
puts "first done"
puts "second run"
def second_run(i)
puts i
raise StopIteration if i==10
end
i=0
loop do
second_run(i)
i+=1
end
puts "second done"下面是另一个用例,它使用了当枚举器到达末尾时Enumerator.next抛出StopIteration错误的事实:
enum = 5.times.to_enum
loop do
p enum.next
end将打印
0
1
2
3
4感谢Cary提供了这个示例。
发布于 2015-01-05 02:53:18
break关键字有两种用法。
首先:break关键字在块中时,会导致块被传递到的方法返回。如果您将一个参数传递给break,则该方法的返回值将是该参数。下面是一个示例:
def a
puts 'entering method a'
yield
puts 'leaving method a'
end
result = a { break 50 }
puts result这将打印以下内容:
entering method a
50第二:break关键字可能导致while、until或for循环终止。下面是一个示例:
i = 0
result =
while i < 5
i += 1
puts i
break 75 if i == 3
end
puts result这将打印以下内容:
1
2
3
75您的Kernel#loop示例使用了第一种情况,导致loop方法返回。
据我所知,StopIteration是一个例外,它只适用于Kernel#loop。例如:
infinite_loop = Enumerator.new do |y|
i = 0
while true
y << i
i += 1
end
end
infinite_loop.each do |x|
puts x
raise StopIteration if x == 4
end然而,失败是因为StopIteration未被捕获:
x = 0
loop.each do
puts x
x += 1
raise StopIteration if x == 4
end捕获StopIteration并退出。
https://stackoverflow.com/questions/27768641
复制相似问题