Alex Rivera | Logout

How to get a single character without pressing enter?

Asked 2008-10-06T16:06:20.747
47

How can I get a single keyboard character from the terminal with Ruby without pressing enter? I tried Curses::getch, but that didn't really work for me.

Edit
Report

1 Answer

22

@Jay gave a great answer, but there are two problems:

  1. You can mess up default tty state;
  2. You ignore control characters (^C for SIGINT, etc).

A simple fix for that is to save previous tty state and use following parameters:

  • -icanon - disable canonical input (ERASE and KILL processing);
  • isig - enable the checking of characters against the special control characters INTR, QUIT, and SUSP.

In the end you would have a function like this:

def get_char
  state = `stty -g`
  `stty raw -echo -icanon isig`

  STDIN.getc.chr
ensure
  `stty #{state}`
end
answered 2013-01-25T17:49:12.170

Your Answer