【问题标题】:Ruby STDIN.getc does not read char on receptionRuby STDIN.getc 在接收时不读取字符
【发布时间】:2011-11-15 20:45:19
【问题描述】:

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

如果您尝试运行此脚本:

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

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

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

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

【问题讨论】:

标签: ruby stdin getc


【解决方案1】:

an answer from Matz :)

更新

另外,你可以使用名为highline的gem,因为使用上面的例子可能会链接到奇怪的屏幕效果:

require "highline/system_extensions"
include HighLine::SystemExtensions

while k = get_character
  print k.chr
end

【讨论】:

  • +1 引用了 11.5 年前的帖子。 :) 请参阅我链接到的问题以获取更多答案,您可以将这些答案编译到您的答案中。
  • 是的,那个帖子很古老,但你可以看到它仍然是真实的:D
  • 感谢您的快速回答。这让我很开心。它解释了我在其他程序中的一些奇怪行为。
【解决方案2】:

改编自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"

【讨论】:

    【解决方案3】:

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

    require 'io/console'
    
    STDIN.getch.tap { |char| exit(1) if char == "\u0003" }
    

    【讨论】:

      【解决方案4】:

      来自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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-11
        • 2018-08-29
        • 2020-01-13
        • 2021-12-19
        • 1970-01-01
        • 2016-09-30
        • 1970-01-01
        相关资源
        最近更新 更多