How can I use "puts" to the console without a line break in ruby on rails?

RubyIoConsole

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSatchelView Question on Stackoverflow
Solution 1 - RubyidlefingersView Answer on Stackoverflow