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
and
if some_condition
throw :done
end
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.
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.