Search code examples
rubyloopskeypress

Pause an "until" loop and wait for a keypress to continue (Ruby)


I have a method with an until loop that keeps calling another method until a third method returns true. This is basically checking to see if a puzzle is solved.

def call_loop
  until solved?  #returns true if puzzle is solved
    flip         #changes one piece on the board    
  end
end

Is there a way to have this loop pause before each call to the flip method and wait for the user to press the spacebar?


Solution

  • The easy solution would be to add a gets before flip. Then it would wait for you to hit enter.

    If you really want to wait for spacebar, you can use curses. It can do robust input handling in the terminal, but it can get pretty complicated. If you're using Ruby 2.1.0 or earlier curses is part of the stdlib. Otherwise you'll need one of the gems.