Search code examples
rubyexitbreakabort

Breaking from a definition one level up


In the code below, break exits the program totally and returns to irb, while I want to get back to the line where the print statement is.

def f1()
  do_something
end

def f2()
  do_something
end

def f1()
  print "I want to get back here."
  while true
    choice = gets.chomp
    if choice == "exit"
      break
    else
      f2()
    end
  end
end

How do you break just one level up?


Solution

  • Add another loop outside. It may also be simpler to use loop than while true:

    def f1()
      loop do
        print "I want to get back here."
        loop do
          choice = gets.chomp
          if choice == "exit"
            break
          else
            f2()
          end
        end
      end
    end