如何在红宝石中使一位数成为两位数? [英] How to make single digit number a two digit number in ruby?
问题描述
Time.new.month
返回 10 月之前任何月份的一位数表示(例如,6 月是 6
),但我想要一个 2 位格式(即而不是 6
我想要 06
).
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'
推荐答案
对于你的需要我觉得还是最好的
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
以下是所有支持格式的文档:http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-sprintf
Here is the documentation with all the supported formats: http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-sprintf
这篇关于如何在红宝石中使一位数成为两位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!