Search code examples
rubystringnested-loops

Counting up minutes and hours of a day, adding leading zero to min and hour when single digit - Ruby


I would like to count all hour minute possibilities of a day in the 24h format xx:xx (needs to be in String)

However I am struggling with getting the leading zeros:

Here is what I have so far:

24.times { |h| 60.times { |m| puts "#{h}:#{m}" } }

Gives

0:0
0:1
...
0:10
...
1:1
...
10:1
...
23:59

I would like to have leading zeros on both hour and min

00:00  
...
23:59

Can it be done in that one line or do I need to split these loops apart?


Solution

  • You can format numbers like that using the syntax: "0Nd" % i where N is the padding amount (2 in your case) and i is the number you want to pad.

    24.times { |h| 60.times { |m| puts "#{"%02d" % h}:#{"%02d" % m}" } }