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 of
sum> 0is satisfied at the stage of the first addition, At this point
throw (: escape_test)is called to escape ** from both the
j 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
.
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
.
Recommended Posts