How to read a character at a time from STDIN without needing to press return key?

In the following bit of code:

print STDIN.getc
STDOUT.flush

The code for whatever key I type isn’t actually printed out until I go
on to hit the return key. How can I have it printed as soon as I type
a character key?

Thanks,
Ken

-------- Original-Nachricht --------

Datum: Thu, 4 Sep 2008 05:40:43 +0900
Von: Kenneth McDonald [email protected]
An: [email protected]
Betreff: How to read a character at a time from STDIN without needing to press return key?

Ken
Dear Ken,

I found this thread :
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/78856
about the same question …

Best regards,

Axel

Kenneth McDonald wrote:

In the following bit of code:

print STDIN.getc
STDOUT.flush

The code for whatever key I type isn’t actually printed out until I go
on to hit the return key. How can I have it printed as soon as I type
a character key?

Thanks,
Ken

It’s not in Ruby standard. Under Windows you can do it like this:

def read_char
require “Win32API”
Win32API.new(“crtdll”, “_getch”, [], “L”).Call
end

Found here: Ruby Quiz - Sokoban (#5)

TPR.

Hi,

Am Donnerstag, 04. Sep 2008, 05:40:43 +0900 schrieb Kenneth McDonald:

In the following bit of code:

print STDIN.getc
STDOUT.flush

The code for whatever key I type isn’t actually printed out until I go on
to hit the return key. How can I have it printed as soon as I type a
character key?

On feasible operating systems you can install the “termios” gem.
Then say something like:

class IO
def nocanon
term = Termios::getattr self
term.c_lflag &= ~Termios::ICANON
Termios::setattr self, Termios::TCSANOW, term
yield
ensure
term.c_lflag |= Termios::ICANON
Termios::setattr self, Termios::TCSANOW, term
end
end

$stdin.nocanon do
c = $stdin.getc
end

Maybe you like to have a look at how I let the user enter
passwords: http://bertram-scharpf.homelinux.com/src/password.rb.

Good luck!

Bertram

On Sep 3, 2008, at 3:40 PM, Kenneth McDonald wrote:

In the following bit of code:

print STDIN.getc
STDOUT.flush

The code for whatever key I type isn’t actually printed out until I
go on to hit the return key. How can I have it printed as soon as I
type a character key?

http://blog.grayproductions.net/articles/i_just_want_one_character

Hope that helps.

James Edward G. II

Hi,

At Thu, 4 Sep 2008 05:40:43 +0900,
Kenneth McDonald wrote in [ruby-talk:313786]:

In the following bit of code:

print STDIN.getc
STDOUT.flush

The code for whatever key I type isn’t actually printed out until I go
on to hit the return key. How can I have it printed as soon as I type
a character key?

With io-console, you can do:

print STDIN.getch

http://www.rubyist.net/~nobu/ruby/io-console.tar.bz2
http://www.rubyist.net/~nobu/ruby/io-console-0.2.gem