Search code examples
rubystdin

remove and replace the text when putting a string into the console $stdin ruby


I have a program that is a client, talking to a server with socket.

When the user is inputting a message, if another message comes in, it breaks up the text visually, making it hard to understand for the user.

the scenario can be thought up like this

c=0
p=Thread.new do
    loop {
        # this is the messages coming in
        c+=1
        puts c
        sleep 1
    }
end
g=Thread.new do
    loop {
      #this is the user input
      puts $stdin.gets  
    }
end
p.join
g.join

in the case of some really slow typers, the output looked similar to this

1
h2
el3
l4
o5

hello

6

Is there any way to remove and replace the text when putting a string into the console?

edit

So, now if i can get each character separate, i can add it to a string, and in the thread p when it puts, it will put "\r" + c and then print the string.

this would allow the user to still see what they are typing, as well as not interrupting the p thread.

I dont know how to get each character individually.

this also brings up the problem of "how would backspace work?" and "would i need a switch statement for special characters like return and ctrl+c?"


Solution

  • If you are trying to implement a chat app in terminal, the "appropriate" tool is curses. A curses library essentially lets you write a GUI in the terminal. It lets you define separate regions of the screen that you can update separately and also lets you read input without echoing it to the terminal.