I am reading source code for god
A process monitoring framework in Ruby and found this STDOUT.sync = true
. I've never seen something like this before.
Please explain what it does, what the point of this line?
Thanks in advance.
Per default, puts
does not write immediately to STDOUT
, but buffers the strings internally and writes the output in bigger chunks. This is done because IO operations are slow, and usually it is not required to output every single character immediately to the console.
This behavior leads to problems in certain situations. Imagine you want to build a progress bar (run a loop that outputs single dots between extensive calculations). With buffering, the result might be that there isn't any output for a while, and then suddenly multiple dots are printed at once.
To disable buffering and instead write immediately to STDOUT
you can set STDOUT
into sync mode like this:
STDOUT.sync = true
From the docs:
Sets the sync mode for the stream to the given value; returns the given value.
Values for the sync mode:
true
: All output is immediately flushed to the underlying operating system and is not buffered internally.
false
: Output may be buffered internally.