Is there a way to exit two loops with one command in Ruby?
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
source to share