2

I'm trying to read one character at a time in a ruby running in cygwin.

STDIN.getc returns the characters but only after I pressed enter:

STDOUT.sync = true
while true
    STDIN.getc
    puts "HELLO"
    STDOUT.flush
end

test session:

aa
HELLO
HELLO
HELLO

How can I read a character?

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • 1
    Since Cygwin, look at this answer http://stackoverflow.com/questions/174933/how-to-get-a-single-character-in-ruby-without-pressing-enter/174967#174967 – dexter Sep 06 '11 at 12:45
  • @dexter: working alone in a simple test app, but when I put it in my app ruby crashes :/ – Karoly Horvath Sep 06 '11 at 13:02

1 Answers1

0

use io-console, at later Ruby1.9.3

require 'io/console'

# input 3 chars and escape

buf = ''
3.times do
  buf << STDIN.getch
end

print "Your input is '#{buf}'"
kachick
  • 371
  • 2
  • 7