Vijay Vijay - 5 months ago 13
Ruby Question

Is there a Way To Exit Two Loops by Single Command In Ruby?

Here is the Sample code,

while true
while true
exit all loops when condition true
end
end


Can someone tell me if is it possible here to exit first loop when second loop breaks, but then I want to use only one break command and no raise.

Answer

You know what's better than using only one break? Not using any at all! :)

Little-used throw/catch is good here

catch(:done) do 
  while cond1
    while cond2
      throw :done if condition
    end
  end
end

For more information, see the docs on throw and catch.