【问题标题】:Tell Ruby Display a Line before going to next etc告诉 Ruby 在进行下一步之前显示一行
【发布时间】:2014-11-14 12:42:19
【问题描述】:

我知道您可以使用 sleep(2) 在代码显示前暂停 x 时间,但我希望它逐行执行和显示代码。例如:

x = 1
y = 2

puts x + y #I want this line to show first
sleep(5) #Above line shows but waiting 5 seconds before showing below
puts x + y * 2 #After 5 seconds this line shows
sleep(10) #After 10 seconds etc
puts (x + y) * 2

这在 C 编程中很有效,但在 Ruby 中无效。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    这是一个缓冲问题。在使用puts 之前尝试添加$stdout.sync = trueSetting sync to true disables buffering.

    x = 1
    y = 2
    
    $stdout.sync = true
    
    puts x + y
    sleep(5)
    puts x + y * 2
    sleep(10)
    puts (x + y) * 2
    

    或者,您可以每次手动刷新stdout

    x = 1
    y = 2
    
    puts x + y
    $stdout.flush
    sleep(5)
    
    puts x + y * 2 
    $stdout.flush
    sleep(10)
    
    puts (x + y) * 2
    $stdout.flush
    

    For more info on Ruby buffering, check out this well-done answer.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 2023-03-23
      • 2022-12-01
      • 1970-01-01
      • 2018-12-23
      • 2012-07-28
      相关资源
      最近更新 更多