Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Kernel | catch

概要

Kernel#catch(tag) {|tag| .... } -> object

詳細

Kernel.#throwとの組み合わせて大域脱出を行います。要はgoto文的な使い方になります。
主にネストしたループから一気に脱出するのに使用。

サンプルコード
# encoding: utf-8
require 'pp'

ret = catch(:tag) do
  25.times do |i|
    25.times do |j|
      throw :tag, [i, j] if i + j == 30
    end
  end
  puts "@@@@@@@@"
end

print ret
出力

※"@@@@@@@@"の部分が出力されないことが確認できる

[6, 24]