Ruby puts not outputting in real time

孤人 提交于 2019-11-28 05:20:04

问题


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

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 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

Outputs:

5
7
13
29

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.

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.

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.

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?


回答1:


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



来源:https://stackoverflow.com/questions/5944887/ruby-puts-not-outputting-in-real-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!