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

后端 未结 1 1376
梦谈多话
梦谈多话 2020-12-13 07:51

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 us

相关标签:
1条回答
  • 2020-12-13 08:21

    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
    
    0 讨论(0)
提交回复
热议问题