[Ruby] Escape from multiple loops [Nest]

I want to get out of multiple loops at once

Use Kernel. # Throw and Kernel. # Catch.

sum = 0
catch(:escape_test) do
  for i in 1..3
    for j in 1..3
      sum = i + j
      # sum >I want to escape at once when it reaches 0
      throw(:escape_test) if sum > 0
    end
  end
end

p sum
=> 2

ʻI = 1, j = 1Since the condition ofsum> 0is satisfied at the stage of the first addition, At this pointthrow (: escape_test)is called to escape ** from both thej for statement and the ʻi for statement **.

Using the same logic in break for comparison, we get:

sum = 0
for i in 1..3
  for j in 1..3
    sum = i + j
    #Escape from the j loop
    break if sum > 0
  end
end

p sum
=> 4

In this way, break escapes the innermost loop (this time j's for statement), so ʻi's for statement goes around. Since the process ends when ʻi = 3, j = 1, sum = 4.

Bonus: catch return value

sum = 0
c_value = catch(:escape_test) do
  for i in 1..3
    for j in 1..3
      sum = i + j
      # sum >I want to escape at once when it reaches 0
      throw(:escape_test, sum) if sum > 0
    end
  end
end

p c_value
=> 2

In this way, if you pass a value to the second argument of throw, it will be the return value of catch.

reference

Recommended Posts

[Ruby] Escape from multiple loops [Nest]
Ruby Learning # 21 While Loops
Ruby Joins multiple arrays
From Java to Ruby !!
Ruby Learning # 23 For Loops
Try using Cocoa from Ruby
Use C program from Ruby
Use Face API from Ruby
[Ruby] Receive input from console
CHATBOT (Dialogflow) used from Ruby