Dennis Ferguson
Dennis Ferguson

Reputation: 97

Ruby countdown timer

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

Upvotes: 5

Views: 9106

Answers (3)

Dennis Ferguson
Dennis Ferguson

Reputation: 97

I ended up using the first method dax mentioned but removing the %H which allowed me to call it using longer times

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

Upvotes: 0

floum
floum

Reputation: 1159

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

Upvotes: 8

dax
dax

Reputation: 10997

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

Upvotes: 1

Related Questions