Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby STDIN.getc does not read char on reception

Tags:

ruby

stdin

getc

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 ?

like image 670
Martinos Avatar asked Feb 03 '26 15:02

Martinos


1 Answers

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
like image 95
WarHog Avatar answered Feb 05 '26 06:02

WarHog