If I want "00001" instead of "1", apart from writing my own filling zero method, is there any built in method can help me fill in zero for the integer?
+6
A:
puts "%05d" % 1 # 00001
See: String::%, Kernel::sprintf
Here's what's going on. The "%05d"
to the left of the %
is a C style format specifier. The variable on the right side of the % is the thing to be formatted. The format specifier can be decoded like this:
- % - beginning of format specifier
- 0 - Pad with leading zeros
- 5 - Make it 5 characters long
- d - The thing being formatted is an integer
If you were formatting multiple things, you'd put them in an array:
"%d - %s" % [1, "One"] # => 1 - one
Wayne Conrad
2010-01-25 17:10:43
simple and elegant, but I don't understand the code. it seems a little bit strange for me.
Ted Wong
2010-01-25 17:14:13
%d means decimal, which refers to the value after the %, the 05 means to pad zeros to the decimal to make it length 5.
Anthony Forloney
2010-01-25 17:16:21
The formating is based C's printf. It is used by lots of languages so it is worth learning.http://en.wikipedia.org/wiki/Printf
srboisvert
2010-01-25 18:07:42
Awesome, thanks for pointing this out!
Shyam
2010-04-21 11:50:37