What is catch and throw used for in Ruby?

前端 未结 3 1398
囚心锁ツ
囚心锁ツ 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 12:57

    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 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.

提交回复
热议问题