# Searches a 2D matrix and breaks out of all nested iterators instantly using throw/catch.
def search_matrix_catch(matrix, target)
# `catch` establishes a label/symbol scope (:found_target)
catch(:found_target) do
matrix.each_with_index do |row, i|
row.each_with_index do |val, j|
if val == target
# `throw` jumps straight out of all nested loops, returning the coordinates
throw(:found_target, [i, j])
end
end
end
nil # Returns nil if the target is never found
end
end
def run_catch_example
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
target = 50
coords = search_matrix_catch(matrix, target)
if coords
puts "[Catch/Throw] Found target #{target} at row #{coords[0]}, col #{coords[1]}"
else
puts "[Catch/Throw] Target not found."
end
end
run_catch_example()
# run:
#
# [Catch/Throw] Found target 50 at row 1, col 1
#