数字填充作为字符串消息的一部分

时间:2012-12-12 12:11:41

标签: ruby

我希望有一个类似"The time is #{hours}:#{minutes}"的字符串,以便hoursminutes始终为零填充(2位数)。我该怎么办?

5 个答案:

答案 0 :(得分:2)

见ljust,rjust and center here

示例是:

"3".rjust(2, "0") => "03"

答案 1 :(得分:1)

您可以使用时间格式:Time#strftime

t1 = Time.now
t2 = Time.new(2012, 12, 12)
t1.strftime "The time is %H:%M" # => "The time is 16:18"
t2.strftime "The time is %H:%M" # => "The time is 00:00"

或者,您可以使用'%' format operator

来使用字符串格式
t1 = Time.now
t2 = Time.new(2012, 12, 12)
"The time is %02d:%02d" % [t1.hour, t1.min] # => "The time is 16:18"
"The time is %02d:%02d" % [t2.hour, t2.min] # => "The time is 00:00"

答案 2 :(得分:1)

对字符串使用格式运算符:%运算符

str = "The time is %02d:%02d" %  [ hours, minutes ]

Reference

格式字符串与C函数printf中的相同。

答案 3 :(得分:1)

或类似的东西:

1.9.3-p194 :003 > "The time is %02d:%02d" % [4, 23]
 => "The time is 04:23" 

答案 4 :(得分:1)

sprintf一般很有用。

1.9.2-p320 :087 > hour = 1
 => 1 
1.9.2-p320 :088 > min = 2
 => 2 
1.9.2-p320 :092 > "The time is #{sprintf("%02d:%02d", hour, min)}"
 => "The time is 01:02" 
1.9.2-p320 :093 > 

1.9.2-p320 :093 > str1 = 'abc'
1.9.2-p320 :094 > str2 = 'abcdef'
1.9.2-p320 :100 > [str1, str2].each {|e| puts "right align #{sprintf("%6s", e)}"}
right align    abc
right align abcdef