Filling a number as part of a string message

I would like to have a string like "The time is #{hours}:#{minutes}" , so hours and minutes always have zero padding (2 digits). How can i do this?

+1
ruby
source share
5 answers

You can use time formatting: 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" 

Alternatively, you can use string formatting with the '%' 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" 
+1
source share

See here ljust, rjust and center here .

Example:

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

+2
source share

Use the format operator for strings: % operator

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

Link

The format string is the same as in the C printf function.

+1
source share

or something like:

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

sprintf is useful in general.

 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 
+1
source share

All Articles