Back to Blog

$stdout.sync = true to flush output immediately

on July 4, 2009

Try this.

15.times do
2  putc('.')
3  sleep(2)
4end

I was hoping that I will get a dot after every two seconds. But that's not what happens when you run the code. I see nothing for first 10 seconds then I see five dots in one shot. This is not what I wanted.

I started looking around at the documentation for IO class and found the method called sync= which if set to true will flush all output immediately to the underlying OS.

The reason why OS does not flush immediately is to minimize the IO operation which is usually slow. However in this case you are asking OS to not to buffer and to flush the output immediately.

1$stdout.sync = true
25.times do
3  putc('.')
4  sleep(2)
5end

You might also like

If you liked this blog post, check out similar ones from BigBinary