如何在ruby on rails中使用“put”到控制台而不中断行?

时间:2022-07-31 20:45:09

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 ".".

我有一个通过循环的方法——我希望它输出一个“。”每个循环,这样我就可以在控制台上看到它。但是,当我使用put“.”时,它会在每个句尾加上一个换行符。

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

如果有一种方法让它有一条连续的直线?

1 个解决方案

#1


178  

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...

你需要使用打印而不是put。此外,如果您想让这些点看起来更平滑,您需要在每次打印后刷新stdout缓冲区……

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...

编辑:我只是在查看flush的背后的原因,以回答@rubyprince的评论,并意识到这可以通过简单地使用$stdout来清理一下。同步= true……

$stdout.sync = true

100.times do
  print "."
  sleep 1
end

#1


178  

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...

你需要使用打印而不是put。此外,如果您想让这些点看起来更平滑,您需要在每次打印后刷新stdout缓冲区……

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...

编辑:我只是在查看flush的背后的原因,以回答@rubyprince的评论,并意识到这可以通过简单地使用$stdout来清理一下。同步= true……

$stdout.sync = true

100.times do
  print "."
  sleep 1
end