puts vs print in ruby
I discovered something a bit peculiar about the puts and print methods in Ruby. puts seems to flush immediately, and therefore shows up on $stdout right away. Take the code example below:
5.times { puts "." sleep 2 }
This functions exactly the way that you would expect. It places a single period on $stdout, followed by a two second pause for five iterations. puts inserts a new line character as well, so instead of placing each period on the same line, each one is on a new line. print does not insert the automatic newline sequence, so it would place each one on the same line. However, the code below does not function the way you would expect.
5.times { print "." sleep 2 }
The code above waits for 10 seconds and then prints all 5 periods. As it turns out, this is because the print method buffers the output. The easiest way to get around this (for a situation like the above) is to set the sync property on $stdout.
STDOUT.sync = true 5.times { print "." sleep 2 }
This sets $stdout to avoid buffering the input, which most modern operating systems do. If you find yourself in a situation where you need to have a small amount of output sent immediately to the screen, this is a good technique to utilize to serve this requirement.
Wow that’s cool. i’d imagine it flushes because of the added “\n” at the end? Nice tip
Thx for ‘STDOUT.sync = true ‘ because puts and print waits for 10 seconds and then prints 5 dots.
I don’t know why my ruby do somethings like that when you say that is a difference between puts and print.
But all is fixed thx to you!!
PS: Sorry for my english
Superb tip…..thanks a lot…..
I tried on my computer. That’s no problem for prints to print a dot every 2 seconds. And then I check the value of STDOUT.sync, it’s true.
So I think the value maybe vary in different systems. It would be better to check it before writing this kind of codes.
it also works for STDOUT.sync=false
why?
What happens if you …
5.times {
print “.”
sleep 2
}
puts “:”
On my system, the last ‘puts’ flushes the prior prints.
What I was really after was that the . printed with the 2 second delay. If the last puts flushes the prior prints, then they all show up at once, instead of at 2 second intervals.


