ruby - 输入&IOError : byte oriented read for character buffered IO

标签 ruby

In the one answer我发现这个节等待您的输入并打印它,直到您按 Enter 键:

require 'io/console'
require 'io/wait'

loop do
  chars = STDIN.getch
  chars << STDIN.getch while STDIN.ready?       # Process multi-char paste
  break if chars == ?\n
  STDOUT.print chars
end

但是要想退出loop ,我必须按“Enter”(新行键 - \n )两次,或者在其后按其他内容。
当我尝试再次执行相同的循环(将其复制粘贴到同一个 pry session 中)时,我得到:

IOError: byte oriented read for character buffered IO

chars << STDIN.getch while STDIN.ready?导致上面提到的错误。如果没有这一行,Ruby 就不会显示任何错误。

在这两种情况下(有或没有上面的行),在循环中:

  • 当我按 Enter 键,然后按某个字母(例如“z”)时,我收到此错误。
    在下一个循环中,上面的字母将显示(没有我的输入)。

  • 当我按两次回车键时 - 没有错误,它将退出。
    在下一个循环中,当我按某个字母时,将显示错误。
    在下一个循环中,上面的字母将显示

我记得在 C 或 C++ 中有 flush这样你就可以清空缓冲区。我找到了一些方法,并尝试了这样的方法:

 loop do
   STDIN.ioflush
   STDOUT.ioflush
   STDOUT.iflush
   STDIN.iflush
   STDOUT.oflush
   STDIN.oflush

   chars = STDIN.getch
   chars << STDIN.getch while STDIN.ready?
   break if chars == ?\n
   STDOUT.print chars
 end

但是没有成功。

如何使用输入和第二个字母 & IOError 解决此行为。我认为两者在某种程度上是相关的。

最佳答案

该答案中的代码是我为个人使用而编写的类似 highline 的库的简化版本。我自己从未遇到过该特定错误,但这可能是由于我实际上使用的东西略有不同。我的实际代码更像是这样的:

require 'io/console'
require 'io/wait'

catch(:done) do
  loop do
    chars = STDIN.getch
    chars << STDIN.getch while STDIN.ready?       # Process multi-char paste
    throw :done if ["\r", "\n", "\r\n"].include?(chars)
    STDOUT.print chars
  end
end
STDOUT.print "\n"

我还有终止信号处理程序,以防按下 Ctrl+C(终止进程)或 Ctrl+D(输入结束);第一个中断程序,第二个被连线以使用react,就像按下 Enter 键一样。

精确的行为可能取决于操作系统(我在 OSX 和 FreeBSD 上使用它),因为 Enter 键可能返回 "\r""\n" 中的任何一个code> 或 "\r\n" 取决于操作系统:

\r\n , \r , \n what is the difference between them?

关于ruby - 输入&IOError : byte oriented read for character buffered IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21456829/

相关文章:

javascript - 如何使用<audio>标签html5再现声音序列

java - 验证硬退回的电子邮件 ID

ruby-on-rails - 多边形 rgeo 中的点

ruby-on-rails - 使用 Active_record Dirty : Before @example. 更新(model_params)进行更改检测?

Ruby on Rails 上传文件问题 奇数 utf8 转换错误

javascript - 无法将 Javascript 变量设置为 Ruby 变量值

ruby - 将自定义随机数生成器与 Ruby Array#shuffle/sample 一起使用

ruby-on-rails - rails 错误 method_missing':Gem::Specification 的未定义方法 `this'

ruby - 如何减少 Ruby 的 if 条件?

ruby-on-rails - pg gem sslmode=verify-full,在哪里放置证书?