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?

Answers


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.


Need Your Help

Wordpress custom options not being saved

php wordpress wordpress-theming

I'm having problems with adding a custom settings page for wordpress, and more specifically getting the options to save.

join/leave multicast group using libpcap

linux networking network-programming multicast libpcap

I need to receive a multicast stream but filter incoming packets by source MAC address on CentOS 5.5.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.