Alexander Abramovich
Alexander Abramovich

Reputation: 11438

Number padding as a part of string message

I would like to have a string like "The time is #{hours}:#{minutes}", so that hours and minutes is always zero-padded (2 digits). How can I do it please?

Upvotes: 1

Views: 128

Answers (5)

BernardK
BernardK

Reputation: 3734

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

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

You could 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 using the '%' 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"

Upvotes: 1

Nicolas Dusart
Nicolas Dusart

Reputation: 2007

Use the format operator for strings: the % operator

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

Reference

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

Upvotes: 1

codenut
codenut

Reputation: 56

or something like:

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

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

See ljust, rjust and center here.

Example would be:

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

Upvotes: 2

Related Questions