tags:

views:

244

answers:

4

I'm outputting a set of numbered files from a Ruby script. The numbers come from incrementing a counter, but to make them sort nicely in the directory, I'd like to use leading zeros in the filenames. In other words,

file_001...

instead of

file_1

Is there a simple way to add leading zeros when converting a number to a string? (I know I can do "if less than 10.... if less than 100")

+6  A: 

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

Daniel Martin
Great! So "%s" means "substitute the Nth value here," and "%03d" means "substitute a number here, adding as many zeros as needed to make it a 3-digit number?" (I'm guessing the d means "digits.") I see the documentation on this now (http://www.ruby-doc.org/core/classes/String.html#M000770), but it's very concise and I'd like a little elaboration.
Nathan Long
I added a link to a printf format cheat sheet. "s" means "string", "d" means "decimal number". The "03", means "pad to 3 characters with zeros"; "%3d" would pad on the left with spaces.
Daniel Martin
Great! Thanks for the helpful explanation.
Nathan Long
+1  A: 

Cant you just use string formatting of the value before you concat the filename?

"%03d" % number
Ólafur Waage
+2  A: 

If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do

str = "file_" + i.to_s.rjust(n, "0")
neutrino
Heh heh, not the best answer, but I didn't know about rjust and I've been using ruby for years. Cheers!
pauliephonic
A: 

I had a similar need i.e., generate several files with incrementing filenames such that i have file_001 instead of file_1. What i did was used a string for the counter and used "next". e.g.,

n = "001"
filename = "file_" + n
n = n.next
testr