Monday, May 13, 2019

Detecting key press in Ruby

To check whether a key is pressed in linux (non-blocking, non-waiting).
def keypressed
  system('stty raw -echo') # => Raw mode, no echo
  char = (STDIN.read_nonblock(1).chr rescue nil)
  system('stty -raw echo') # => Reset terminal mode
  char
end
Inspired on https://stackoverflow.com/a/22659929.