Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Sunday, March 28, 2010

How to Get Each Characters

STDIN.getc returns a buffered character from STDIN. How do I get a character from STDIN immediately without buffering?

This code looks well, but it doesn't work as you expect. The input characters will be still buffered.

STDIN.sync = true
p STDIN.getc


require 'curses'
p Curses.getch

This works, but there is an undesired side-effect. Curses.getch clears the screen.

stty raw

orig_stty = `stty -g`
system 'stty raw echo'
p STDIN.getc
system 'stty', orig_stty

This works, but some platform don't support the command.


Getting a character immediately looks easy, but it actually isn't easy.

No comments:

Post a Comment