Ruby 不实时输出 [英] Ruby puts not outputting in real time

查看:79
本文介绍了Ruby 不实时输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Project Euler 上遇到了一些问题.问题之一:

I've started some problems on Project Euler. One of the questions:

13195 的质因数是 5、7、13 和 29.数 600851475143 的最大质因数是多少?

我写了一些代码......它有效:

I have some code written up...and it works:

class Integer

  def primeFactors
  load('/home/arseno/ruby/lib/prime.rb')
  a = []

    for i in (1..self)
      div = self.to_f/i.to_f
      if((div==div.to_i)&&(Prime.prime?(i)))
        a << i
      end
    end
  a
  end
end

puts 13195.primeFactors

输出:

5
7
13
29

到目前为止一切顺利!现在,当我输入 600851475143 时,我的终端挂了(理所当然,它正在计算很多东西!)所以我试图做的是将 puts i 放在循环中/如果,以便我在迭代时捕获输出......实时.

So far so good! Now, when I put in 600851475143 instead, my terminal hangs up (rightfully so, it's computing a whole lot of stuff!) So what I attempted to do was to put a puts i within the loop/if, so that I capture the output as it iterated through...in real time.

但是通过将这个 puts i 放入循环中,Ruby 不会在整个迭代过程中输出变量;相反,它会保留某种缓冲区中的值,并在计算完成时将其刷新.

But by putting this puts i into the loop, Ruby does not output the variable throughout the iteration; instead, it holds onto the values in some kind of buffer and flushes them out when the computation is complete.

这个特殊问题需要 Ruby 永远计算(它已经运行了 10 分钟),我怀疑它是在浮点转换中.

This particular problem is taking forever for Ruby to compute (it's been running for 10 minutes), I suspect it is in the float conversions.

为什么 Ruby(我的终端?)一直保留这些值直到计算结束?我可以在找到它们时实时查看这些值吗?你有更好的方法吗?

Why is Ruby (my Terminal?) holding onto the values until end of computation? Can I see the values in real time as it finds them instead? Do you have a better way of doing this?

推荐答案

尝试添加 STDOUT.sync = true.您也可以在 puts 之后尝试 STDOUT.flush.更多信息请此处.

Try adding a STDOUT.sync = true. You could also try STDOUT.flush after the puts. Some more info here.

这篇关于Ruby 不实时输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆