如何在红宝石中使一位数成为两位数? [英] How to make single digit number a two digit number in ruby?

查看:25
本文介绍了如何在红宝石中使一位数成为两位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆