Enter & IOError: byte-oriented read for character buffered by IO

In one answer, I found this stanza that waits for your input and prints it until you hit 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

However, to exit loop, I must press Enter twice (the key for a new line - \n) or press something else after it. When I try to execute the same loop again (copy it to the same session), I get:

IOError: byte oriented read for character buffered IO

chars << STDIN.getch while STDIN.ready?trigger the raise mentioned above error. Without this line, ruby ​​simply does not show any errors.

In both cases (with and without the line above) in the loop:

  • when I press the enter key and then some letter (for example, "z"), I get this error.
    In the next cycle above, a message will be shown (without my input).

  • - , .
    , - , .

, 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

.

2- IOError. , - .

+2
1

- , . , , - . :

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"

kill-signal, Ctrl + C ( kill) Ctrl + D ( ); , - , .

( OSX FreeBSD), "\r", "\n" "\r\n" :

\r\n,\r,\n ?

+2

All Articles