Ruby STDIN。getc在接收端不读取char

时间:2021-07-19 07:31:17

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

在返回chars之前,Ruby IO . getc似乎一直等待直到收到一个\n。

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.

它将返回发送到stdin的每个字符一个“到达”字符,但只在发送了一个\n之后。

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

似乎所有的char都被缓冲了,即使我写STDIN。同步= true。

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

有没有人知道如何在一个字符被发送到STDIN之后,让脚本打印“Char arrived”?

2 个解决方案

#1


8  

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:

此外,您可以使用名为highline的gem,因为上面的例子可能与奇怪的屏幕效果有关:

require "highline/system_extensions"
include HighLine::SystemExtensions

while k = get_character
  print k.chr
end

#2


2  

Adapted from from another answered question.

改编自另一个回答的问题。

def get_char
  begin
    system("stty raw -echo")
    str = STDIN.getc
  ensure
    system("stty -raw echo")
  end
  str.chr
end

p get_char # => "q"

#1


8  

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:

此外,您可以使用名为highline的gem,因为上面的例子可能与奇怪的屏幕效果有关:

require "highline/system_extensions"
include HighLine::SystemExtensions

while k = get_character
  print k.chr
end

#2


2  

Adapted from from another answered question.

改编自另一个回答的问题。

def get_char
  begin
    system("stty raw -echo")
    str = STDIN.getc
  ensure
    system("stty -raw echo")
  end
  str.chr
end

p get_char # => "q"