3

似乎 Ruby IO#getc 等到​​收到 \n 后再返回字符。

如果您尝试运行此脚本:

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

每个发送到标准输入的字符都会返回一个“字符到达”,但只有在发送了 \n 之后。

即使我写 STDIN.sync = true,似乎所有字符都被缓冲了。

有谁知道如何在将 char 发送到 STDIN 后立即使脚本打印“Char 到达”?

4

4 回答 4

8

Matz给出了答案:)

更新

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

require "highline/system_extensions"
include HighLine::SystemExtensions

while k = get_character
  print k.chr
end
于 2011-11-15T20:57:43.773 回答
2

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

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

p get_char # => "q"
于 2011-11-15T21:04:37.340 回答
0

https://stackoverflow.com/a/27021816/203673及其评论是 ruby​​ 2+ 世界中的最佳答案。这将阻止读取单个字符并在按下 ctrl + c 时退出:

require 'io/console'

STDIN.getch.tap { |char| exit(1) if char == "\u0003" }
于 2019-07-25T15:48:03.347 回答
0

来自 https://flylib.com/books/en/2.44.1/getting_input_one_character_at_a_time.html

def getch
  state = `stty -g`
  begin
    `stty raw -echo cbreak`
    $stdin.getc
  ensure
    `stty #{state}`
  end
end

while (k = getch)
  print k.chr.inspect
  sleep 0.2
end
于 2020-05-14T17:15:36.110 回答