Is there a way to exit two loops with one command in Ruby?

Here is some sample code,

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

      

Can anyone tell me if it is possible here to break out of the first loop when breaking the second loop, but then I only want to use one break command and no boost.

+3


source to share


2 answers


Do you know what's better than using just one break

? Don't use at all! :)

Small 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 at throw

and catch

.

+7


source


Ok, so obviously boolean flags are not-go. Unfortunately.

Another thing that comes to mind is an error, but you said you didn't want to do that, or wrap it in a method and return it. To be honest, it looks like there is no way, but here's the simplest I could think of:

catch (:exit) do
    while true
        while true
            throw :exit if condition
        end
    end
end

      

You can also throw an exception, but that seems dirty. Here's the code to do it though:



begin
    while true
        while true
            raise "Exiting loops" if condition
        end
    end
rescue
    #Code to go after the loop
end

      

Finally, you can wrap the whole thing in a method and return from that method:

def my_descriptive_method_name()
    while true
        while true
            return if condition
        end
    end
end

      

+1


source







All Articles