tags:

views:

72

answers:

2

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

But what is this useful for? Can somebody please give me an example of what catch and throw statements are used for in Ruby?

+1  A: 

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

If you had used a break statement above, it would have broke 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.

Bragboy
+1  A: 

I have been looking for a good example for a while, until I met Sinatra. IMHO, Sinatra exposes a very interesting example usage for catch.

In Sinatra you can immediately terminate a request at any time using halt.

halt

You can also specify the status when halting...

halt 410

Or the body...

halt 'this will be the body'

Or both...

halt 401, 'go away!'

The halt method is implemented using throw.

def halt(*response)
  response = response.first if response.length == 1
  throw :halt, response
end

and catched by the invoke method.

There are several uses of :halt in Sinatra. You can read the source code for more examples.

Simone Carletti