1

のような文字列が欲しい"The time is #{hours}:#{minutes}"ので、hours常にminutesゼロが埋め込まれます(2桁)。どうすればいいですか?

4

5 に答える 5

2

ここでljust、rjust、centerを参照してください。

例は次のとおりです。

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

于 2012-12-12T12:14:50.630 に答える
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"

または、 「%」フォーマット演算子を使用して文字列フォーマットを使用することもできます

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"
于 2012-12-12T12:13:32.330 に答える
1

文字列にはフォーマット演算子を使用します:%演算子

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

参照

フォーマット文字列は、C関数printfと同じです。

于 2012-12-12T12:14:58.493 に答える
1

または次のようなもの:

1.9.3-p194 :003 > "The time is %02d:%02d" % [4, 23]
 => "The time is 04:23" 
于 2012-12-12T12:15:21.973 に答える
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
于 2012-12-12T12:43:25.980 に答える