How can I output leading zeros in Ruby?

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 Answers
6

Leave a Comment