Ruby 中的 catch 和 throw 是干什么用的? [英] What is catch and throw used for in Ruby?
问题描述
在大多数其他语言中,catch 和 throw 语句的作用与 Ruby 中的 begin、rescue 和 raise 语句的作用相同.我知道你可以用这两个语句来做到这一点:
In most other languages, the catch and throw statements do what the begin, rescue, and raise statements do in Ruby. I know the you can do this with these two statements:
catch :done do
puts "I'm done."
end
和
if some_condition
throw :done
end
但这有什么用?有人能给我举个例子,说明在 Ruby 中使用什么 catch 和 throw 语句吗?
But what is this useful for? Can somebody please give me an example of what catch and throw statements are used for in Ruby?
推荐答案
您可以使用它来打破嵌套循环.
You can use this to break out of nested loops.
INFINITY = 1.0 / 0.0
catch (:done) do
1.upto(INFINITY) do |i|
1.upto(INFINITY) do |j|
if some_condition
throw :done
end
end
end
end
如果您在上面使用了 break 语句,它就会跳出内部循环.但是如果你想跳出嵌套循环,那么这个 catch/throw 将非常有帮助.我用它这里来解决其中之一欧拉问题.
If you had used a break statement above, it would have broken out of the inner loop. But if you want to break out of the nested loop, then this catch/throw would be really helpful. I have used it here to solve one of the Euler problems.
这篇关于Ruby 中的 catch 和 throw 是干什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!