What is catch and throw used for in Ruby?

前端 未结 3 1397
囚心锁ツ
囚心锁ツ 2020-12-25 12:19

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:

3条回答
  •  一整个雨季
    2020-12-25 13:22

    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 caught by the invoke method.

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

提交回复
热议问题