mko mko - 1 year ago 79
Ruby Question

How to make single digit number a two digit number in ruby?
returns a single digit representation of any month prior to October (e.g. June is
), but I want a 2-digit format (i.e. instead of
I want

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'

Answer Source

For your need I think the best is still


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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download