如何修正 Ruby 倒计时器?

Ufu*_*ldi 0 ruby time timer carriage-return countdown

import time

def countdown(time_sec):
  while time_sec:
    mins, secs = divmod(time_sec, 60)
    timeformat = "{:02d}:{:02d}".format(mins, secs)
    print(timeformat, end='\r')
    time.sleep(1)
    time_sec -= 1

  print("Time ended.")
Run Code Online (Sandbox Code Playgroud)

您在上面看到的这段 Python 代码运行顺利,并从给定的 开始倒计时time_sec。此代码还每秒清洁屏幕。我想编写在 Ruby 中工作完全相同的代码。

#timer.rb(Ruby codes) here
def countdown time_sec
    
    while time_sec
        mins, secs = time_sec.divmod(60)[0], time_sec.divmod(60)[1]
        timeformat = "%02d:%02d" % [mins, secs]
        puts "#{timeformat}\r"
        sleep(1)
        time_sec -= 1
    end
    
    puts "Time is ended."
end 
Run Code Online (Sandbox Code Playgroud)

您在上面看到的这段 Ruby 代码以错误的方式工作。首先,秒数被依次打印。但我想像上面的 Python 代码一样更新单行。其次,当运行此 Ruby 代码并达到倒计时时00:00,它会继续从 开始倒计时-01:59。我该如何更正此代码?

ste*_*lag 7

您正在使用puts,它会添加行结尾并弄乱\r. 此外,Python 代码会一直运行,直到 time_sec 为零,此时计算结果为 false 并导致循环停止。在 Ruby 中,零不会被视为 false。

def countdown(time_sec)
  time_sec.downto(0) do |t|
    print "%02d:%02d\r" % t.divmod(60)
    sleep 1
  end
end
Run Code Online (Sandbox Code Playgroud)