Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make single digit number a two digit number in ruby?

Time.new.month returns a single digit representation of any month prior to October (e.g. June is 6), but I want a 2-digit format (i.e. instead of 6 I want 06).

I wrote the following solution, and I am asking to see some other/better solutions.

s = 6.to_s; s[1]=s[0]; s[0] = '0'; s #=> '06'
like image 634
mko Avatar asked Jun 18 '11 16:06

mko


2 Answers

For your need I think the best is still

Time.strftime("%m")

as mentioned but for general use case the method I use is

str = format('%02d', 4)
puts str

depending on the context I also use this one which does the same thing:

str = '%02d %s %04d' % [4, "a string", 56]
puts str

Here is the documentation with all the supported formats: http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-sprintf

like image 135
Schmurfy Avatar answered Oct 11 '22 21:10

Schmurfy


You can use this printf-like syntax:

irb> '%02d' % 6
=> "06"

or

str = '%02d' % 6

So:

s = '%02d' % Time.new.month
=> "06"

See the documentation for String#%.

like image 41
Mat Avatar answered Oct 11 '22 19:10

Mat