Output to the console while saving user input in ruby

I have a ruby ​​script that simultaneously and asynchronously receives and displays messages from the server and allows you to enter the user on the console. When a message is received, it is currently recorded in the middle of what the user enters. The input itself is not distorted, but it looks awful. Ideally, this will save the current user input, display a message, and then restore the input to the next line. I did this with c, intercepting every stroke, but all I remember is that it was a big problem. I'm new to ruby, so I'm not sure if there is a good way to do this or how to do it.

Example: the user enters >abcde, and the message helloarrives, and the user enters fghafter. Now the console will show:

>abcdehellofgh

and the user can continue typing at the end. I would like it to show:

hello
>abcdefgh
+5
source share
2 answers

Two important parts of my proposal:
1. system ("stty raw -echo") #, to instantly get any typed character in combination with 2. using STDIN.getc with string-var, which serves as an input buffer for retyping user input.

9 (& boolean variable incoming_message) .
( , , .)

x .

:

$ ruby simultaneous_input_and_output.rb
Hello World!9
The incoming message is: true
Hello World!9x

You entered:
Hello World!9x
End!



#!/usr/bin/ruby

$input_buffer = "";  
incoming_message = false

begin  
  system("stty raw -echo")  

  begin   
    str = STDIN.getc  
    print str.chr  

    $input_buffer = $input_buffer + str.chr  
    if str.chr == '9'  
      incoming_message = true  
    end  
    if incoming_message   
      puts "\nThe incoming message is: " + incoming_message.to_s  
      print $input_buffer  
      incoming_message = false  
    end  
  end while (str.chr != 'x')  
ensure  
  system("stty -raw echo")  
end  

puts "\n\nYou entered:"   
puts $input_buffer  
puts "End!"    

P.S.: ( "stty raw -echo" ) . (User Jay) ?

+2

.

. , , .

, - - YAML, , Ruby, - .

( , .)

+1

All Articles