Home > database >  How to correct Ruby countdown timer?
How to correct Ruby countdown timer?

Time:06-07

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

This Python codes you see above work smootly and count down from given time_sec. This codes also clean screen every second. I would like to write codes which are work exactly same in 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 = "d:d" % [mins, secs]
        puts "#{timeformat}\r"
        sleep(1)
        time_sec -= 1
    end
    
    puts "Time is ended."
end 

This Ruby codes you see above work in wrong way. Firstly seconds are printed one after the other. But I would like to update single line like above Python codes do. Secondly when this Ruby codes is run and countdown reached 00:00, It keeps counting down from -01:59. How can I correct this code?

CodePudding user response:

You are using puts, which adds a line ending and messes up the\r. Futhermore, the Python code runs until time_sec is zero, which evaluates as false and causes the loop to stop. In Ruby zero does not evaluate as false.

def countdown(time_sec)
  time_sec.downto(0) do |t|
    print "d:d\r" % t.divmod(60)
    sleep 1
  end
end
  • Related