1

What command/keyword is used to check for keyboard input without stopping execution? I want to build a loop that will run continuously, and at every iteration of the loop, I want to check for keyboard input. If the user presses the right key, my program will act on it; if not, it will continue to run.

EDIT I want it to work with out pressing the enter key. Like when a game runs it checks if the user presses the arrow key then acts on the key press or continues if nothing is pressed.

Michael
  • 185
  • 1
  • 10

2 Answers2

1

From what I could find and some hacking around, I managed to put together something that will immediately echo the keys you press when running in command line.

require 'io/console'
loop do
  p STDIN.getch
end

But as the referenced answer mentions, you'll want to capture SIGTERMs so you don't get trapped in the program: Signal.trap("INT") { exit }

So the meat of your program and all of its processing lives in that main loop, and each go around of that loop it will grab a character from the STDIN.

Community
  • 1
  • 1
Alexis Andersen
  • 785
  • 6
  • 12
  • Thank You. This works for all the alphanumeric and punctuation keys. It does not display the arrow keys, backspace, or the enter key. The most important thing is you have sent me down the right path and given me the tools I need to adapt my idea if necessary. – Michael Feb 10 '15 at 21:26
0

You cannot do that with a simple method. The most common way to do that is to use the curses gem.

sawa
  • 165,429
  • 45
  • 277
  • 381