Multiple Line Issues When Using STDIN.gets

Having looked at this question, I have the following code:

$/ = "\0"
answer = STDIN.gets

Now I was hoping this would allow the user:

  • enter multi-line input ending with a tap Ctrl-D.
  • enter a single line input ending with a tap Ctrl-D.
  • enter "nothing" completion by tapping Ctrl-D.

However, the behavior that I really see is as follows:

  • User can enter multi-line input.
  • The user may not enter single line input, unless they press Ctrl-D twice .
  • The user can enter "nothing" if he immediately hits Ctrl-D.

So, why is the situation with a single line (i.e. if the user entered some text, but does not have a new line, and then clicked Ctrl-D), two clicks are required Ctrl-D? And why does it work then if the user does not enter anything? (I noticed that if they do not enter anything and fall into Ctrl-D, I do not get an empty string, but the class is nil - I found this when I tried to call .empty?as a result, since it suddenly failed terribly. This is a way to make it also return an empty string, this would be nice. I prefer checking .empty?on ==and don't really want to define .empty?for the class nil.)

. " ", Ruby, 200 . , "" - "". , "\n" s, , .

+3
2

- . . . , . Solaris:

#!/usr/bin/env ruby
# store the old stty settings
old_stty = `stty -g`
# Set up the terminal in non-canonical mode input processing
# This causes the terminal to process one character at a time
system "stty -icanon min 1 time 0 -isig"
answer = ""
while true
  char = STDIN.getc
  break if char == ?\C-d # break on Ctrl-d
  answer += char.chr
end
system "stty #{old_stty}" # restore stty settings
answer

, stty , , .

+2

STDIN STDIN .

tty Control-D (EOF) EOF, . , , EOF.

, - . ( - ) ,

#!/usr/bin/env ruby

answer = ""
while true
  begin
    input = STDIN.sysread(1)
    answer += input
  rescue EOFError
    break
  end
end

puts "|#{answer.class}|#{answer}|"

: -

INPUT <CR> < Ctrl-D >

|String|This is a line
|

INPUT < Ctrl-D >

|String|This is a line|

< Ctrl-D >

|String||
+2

Source: https://habr.com/ru/post/1765109/


All Articles