How to break out of multiple for loops at once in Ruby

2 Answers

0 votes
# 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
#

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz
0 votes
# Helper method that handles nested iteration and returns early
def find_coordinates(matrix, target)
  matrix.each_with_index do |row, i|
    row.each_with_index do |val, j|
      if val == target
        # Returning immediately exits the method and stops all nested iterations
        return [i, j]
      end
    end
  end
  nil
end

def run_return_example
  matrix = [
    [5, 12, 19],
    [22, 35, 41],
    [50, 68, 74]
  ]

  target = 35
  coords = find_coordinates(matrix, target)

  if coords
    puts "[Method Return] Found target #{target} at row #{coords[0]}, col #{coords[1]}"
  else
    puts "[Method Return] Target not found."
  end
end

run_return_example()


# run:
#
# [Method Return] Found target 35 at row 1, col 1
#

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz
...