174

I have a method which goes through a loop -- I want it to output a "." each loop so I can see it in the console. however, it puts a linebreak at the end of each when I use puts ".".

If there a way so that it just has a continuous line?

John Topley
  • 113,588
  • 46
  • 195
  • 237
Satchel
  • 16,414
  • 23
  • 106
  • 192

1 Answers1

216

You need to use print instead of puts. Also, if you want the dots to appear smoothly, you need to flush the stdout buffer after each print...

def print_and_flush(str)
  print str
  $stdout.flush
end

100.times do
  print_and_flush "."
  sleep 1
end

Edit: I was just looking into the reasoning behind flush to answer @rubyprince's comment, and realised this could be cleaned up a little by simply using $stdout.sync = true...

$stdout.sync = true

100.times do
  print "."
  sleep 1
end
idlefingers
  • 31,659
  • 5
  • 82
  • 68
  • 6
    Is `$stdout.flush` really needed?..I am using Ruby 1.8.7 and I have done things just with `print` and I had no problems.. – rubyprince Feb 22 '11 at 17:41
  • 7
    It's useful if you're doing something like a progress bar. When you just use `print` by itself, it can come out in blocks because it can be stored in the buffer instead of being written straight away (I don't know exactly why). It may be OS specific, too. – idlefingers Feb 22 '11 at 18:44
  • 2
    I tried it with @stdout.flush...any benefits with using .sync=true instead? – Satchel Feb 24 '11 at 00:43
  • I think setting stdout to `sync` is an overkill to output one string. Then if you app outputs a lot it will be slower. – akostadinov May 11 '17 at 20:44