rubystdingetc

Ruby STDIN.getc does not read char on reception


Seems that Ruby IO#getc wait until receiving a \n before returning the chars.

If you try running this script:

STDOUT.sync = true
STDIN.sync = true
while data = STDIN.getc
  STDOUT.puts "Char arrived"
end

It will return one "Char arrived" per char sent to stdin, but only after a \n has been sent.

Seems that all char are buffered even if I write STDIN.sync = true.

Does anyone knows how to make the script print "Char arrived" right after a char has been sent to STDIN ?


Solution

  • There was an answer from Matz :)

    UPDATE

    Also, you can use gem entitled highline, because using above example may be linked with strange screen effects:

    require "highline/system_extensions"
    include HighLine::SystemExtensions
    
    while k = get_character
      print k.chr
    end