Printing in a Ruby Thread while waiting for input generates weird output
So I was working in Ruby and the idea was to constantly reprint a set of strings over itself until a key is pressed. This is my code for that
frame = "aaaa bbbb cccc dddd" thread = Thread.new do while(true) print frame sleep(0.5) end end thread.run begin system("stty raw -echo") str = STDIN.getc ensure system("stty -raw echo") end thread.kill
When this code executes, it generates the output
aaaa bbbb cccc ddddaaaa bbbb cccc ddddaaaa bbbb cccc ddddaaaa bbbb cccc ddddaaaa bbbb cccc dddd
Obviously, you would think that it should produce
aaaa bbbb cccc dddd
repeating until a key is pressed, and I can't figure out why it doesn't. Thoughts?
The following code works as expected for me, including printing newlines. If it works correctly for you, then you have misidentified the cause of your problems.
swivel = Thread.new do loop do print "Hello\nWorld" sleep 0.5 end end.run puts "Press Enter to Stop" str = STDIN.gets swivel.kill
Edit: When you call stty raw -echo, any \n characters will only go down a line. You need \r\n to first go to the front of a line, and then \n to go down to the next line. Presumably your source file is saved with "unix line endings" (\n only), and so the newlines literally embedded in your string are not sufficient.