Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby countdown timer

Tags:

ruby

I found a countdown timer on this site which works well in linux, but I need this exact thing done in Ruby. I am new to ruby so having trouble figuring this out.

  ==Linux version==

   seconds=20; date1=$((`date +%s` + $seconds)); 
   while [ "$date1" -ne `date +%s` ]; do 
   echo -ne "$(date -u --date @$(($date1 - `date +%s` )) +%H:%M:%S)\r"; 
   done

So far I have tried this which does not give me the desired output

   t = Time.now
    seconds = 30
    date1 = (t + seconds)
    while t != date1
      puts t 
      sleep 1
    end

This gives an output like this which A) is not counting down and B) has date added which I don't want.

  2015-05-28 09:57:18 -0500
  2015-05-28 09:57:18 -0500
  2015-05-28 09:57:18 -0500
  2015-05-28 09:57:18 -0500

I want it to output like the linux version which looks like this

  00:00:30
  00:00:29
  00:00:28
like image 942
Dennis Ferguson Avatar asked May 28 '15 14:05

Dennis Ferguson


2 Answers

Try this, if you just need the output and don't use any Time related info :

30.downto(0) do |i|
  puts "00:00:#{'%02d' % i}"
  sleep 1
end

With time (1st draft) :

t = Time.new(0)
countdown_time_in_seconds = 300 # change this value

countdown_time_in_seconds.downto(0) do |seconds|
  puts (t + seconds).strftime('%H:%M:%S')
  sleep 1
end
like image 172
floum Avatar answered Oct 09 '22 14:10

floum


Try this:

def countdown(seconds)
  date1 = Time.now + seconds
  while Time.now < date1
    t = Time.at(date1.to_i - Time.now.to_i)
    p t.strftime('%H:%M:%S')
    sleep 1
  end
end

This is tacking an extra hour to the time...not sure why that is, but the big thing is to use Time.now the whole way through.

edit if you don't want to use it as a method, you can just use the code inside:

date1 = Time.now + 5 # your time here
while Time.now < date1
  t = Time.at(date1.to_i - Time.now.to_i)
  p t.strftime('%H:%M:%S')
  sleep 1
end
like image 43
dax Avatar answered Oct 09 '22 13:10

dax